Python的时间。睡觉()方法等待的tim数量不正确

2024-04-16 06:23:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我得到:

^{pr2}$

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

我使用的是MacOSX(小牛)、iPython1.2.1(带pylab)、Python2.7.5

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


Tags: 代码in命令fortimeosipythonrange
1条回答
网友
1楼 · 发布于 2024-04-16 06:23:50

根据^{} 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()在其他代码被写入或粘贴和计算之前被计算,这可能需要几秒钟的时间。

但是如果我用一个方法包装它,它的行为和预期的一样:

^{pr2}$

或者写进剧本里:

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

在这种情况下,延迟应该以毫秒为单位,可以在后面的输出中看到。我怀疑它能持续到几秒钟。

相关问题 更多 >