gpt4 book ai didi

Python time.clock() 结果不精确并且偏离

转载 作者:太空宇宙 更新时间:2023-11-03 18:48:06 26 4
gpt4 key购买 nike

我有以下脚本,用于测量几个 sleep 功能的实际耗时。我使用 time.sleep() 来暂停程序,或者使用 Psychopy.core.wait() ,据说它更精确并使用高分辨率计时器。我正在明确测试后者,因为 wait() 函数似乎会引起一些麻烦(例如,暂停程序的时间比应有的时间短)。

from psychopy import core
import time
import scipy
import sys

times1 = []
times2 = []
times3 = []
times4 = []
testtime = 40 # Time to wait (40 ms)
n = 200 # Iterations
print "Starting timing test with", testtime, "ms as reference; running", n, "times."

for i in range(n):
t1 = time.time()
time.sleep(testtime/1000.0)
measurement = (time.time()-t1)*1000
times1.append(measurement)

time.clock()
time.sleep(testtime/1000.0)
measurement = time.clock()
times2.append(measurement)

t1 = time.time()
core.wait(testtime/1000.0)
measurement = (time.time()-t1)*1000
times3.append(measurement)

t1 = time.clock()
core.wait(testtime/1000.0)
measurement = time.clock()
times4.append(measurement)

if i%60==0:
sys.stdout.write(".")

print
print "Low precision with time.sleep()"
print "Average is", scipy.mean(times1)
print "StdDev is", scipy.std(times1)

print
print "High precision with time.sleep()"
print "Average is", scipy.mean(times2)
print "StdDev is", scipy.std(times2)

print
print "Low precision with PsychoPy core.wait()"
print "Average is", scipy.mean(times3)
print "StdDev is", scipy.std(times3)

print
print "High precision with PsychoPy core.wait()"
print "Average is", scipy.mean(times4)
print "StdDev is", scipy.std(times4)

我得到的输出是:

Starting timing test with 40 ms as reference; running 200 times.
....
Low precision with time.sleep()
Average is 39.0950024128
StdDev is 7.77598671811

High precision with time.sleep()
Average is 16.2315164609
StdDev is 9.24644085289

Low precision with PsychoPy core.wait()
Average is 40.830000639
StdDev is 21.7002567107

High precision with PsychoPy core.wait()
Average is 16.3130358691
StdDev is 9.24395572035

time.clock() 返回的时间太短了!这种情况在我们这里的几个系统中都是一致发生的。

有人知道这里发生了什么以及可能导致这种情况的原因吗?

最佳答案

您需要执行与 time.time() 相同的操作,并在 sleep 前保存时钟值并减去它以获得测量结果。正如您所拥有的,您的所有时钟值只是测量自该过程开始以来的时间。

关于Python time.clock() 结果不精确并且偏离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19003270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com