gpt4 book ai didi

Python 的 time.sleep() 方法等待的时间不正确

转载 作者:行者123 更新时间:2023-11-28 20:22:00 25 4
gpt4 key购买 nike

这个问题我遇到过几次;重新启动 python 似乎工作(或 ipython)。但是,例如,这是运行以下代码的一种可能输出:

startt = time.time()
for i in range(4):
time.sleep(1)
print '%.3f'%(time.time()-startt)

我得到:

9.989
10.989
11.990
12.991

为什么要等这么久才开始工作?有时,它会在我运行命令后 10 秒甚至 11 秒时启动。

我正在使用 Mac OS X (Mavericks)、IPython 1.2.1(带有 pylab)、Python 2.7.5

我正在导入:os、cv2、time、random、Quartz、LaunchServies、pdb、sys、appscript 和 numpy。

最佳答案

根据 time.sleep docs :

Suspend execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.

time.sleep 的实际等待时间无法保证,取决于主机系统的加载方式。如果您机器上的某些东西占用了资源,Python 进程可能会延迟直到恢复。

不过,秒级的延迟还是太高了。您是否有机会在 Python 交互式 shell 中尝试这个?如果是这样,它可能会干扰,例如:

>>> import time
>>> startt = time.time()
>>> for i in range(4):
... time.sleep(1)
... print '%.3f'%(time.time()-startt)
...
3.147
4.147
5.147
6.147
>>> startt = time.time()
>>> for i in range(4):
... time.sleep(1)
... print '%.3f'%(time.time()-startt)
...
4.949
5.949
6.949
7.949

因为 startt = time.time() 在其余代码被写入或粘贴和评估之前被评估,这可能需要几秒钟。

但是如果我将它包装在一个方法中,它的行为会如预期的那样:

>>> def test():
... startt = time.time()
... for i in range(4):
... time.sleep(1)
... print '%.3f'%(time.time()-startt)
...
>>> test()
1.000
2.000
3.000
4.000

或放入脚本:

import time

startt = time.time()
for i in range(4):
time.sleep(1)
print '%.3f'%(time.time()-startt)

# $ python test.py
# 1.000
# 2.008
# 3.008
# 4.008

在这种情况下,延迟应该以毫秒为单位,如后面的输出所示。我怀疑它能达到几秒钟。

关于Python 的 time.sleep() 方法等待的时间不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25355257/

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