我想为工作中的销售团队创建一个收入计数器,并且喜欢使用 Python。例如。 Joe Bloggs 将他的目标从 22.1 转移到 23.1(相差 1.0)。我希望计数器在一小时内从 22.1 均匀地跳到 23.1。
我已经创建了这个脚本,它可以很好地计算一分钟(每分钟运行 2 秒);然而,当它应该运行一个小时时,它运行了 47 分钟。
问题:有谁知道为什么我把它设置为一个小时时它运行得更快? sleep 时间不准确吗?
import time
def rev_counter(time_length):
time_start = (time.strftime("%H:%M:%S"))
prev_pp = 22.1
new_pp = 23.1
difference = new_pp - prev_pp
iter_difference = (difference / 100000.) # Divide by 100,000 to show 10 decimal places
time_difference = ((time_length / difference) / 100000.)
i = prev_pp
while i < new_pp:
print("%.10f" % i)
i = i + iter_difference
time.sleep(time_difference)
time_end = (time.strftime("%H:%M:%S"))
print "Time started at", time_start
print "Time ended at", time_end
rev_counter(60) # 60 seconds. Returns 62 seconds
rev_counter(600) # 10 minutes. Returns 10 minutes, 20 secs
rev_counter(3600) # 1 hour. Returns 47 minutes
最佳答案
请注意 time.sleep()
的 Python 文档中的引用
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.
作为一个建议,如果遇到这个问题,我会使用一个变量来跟踪间隔开始的时间。当 sleep 醒来时,检查是否已经过了预期时间。如果不是,则重新启动 sleep 以获得差异等。
关于python - Python 计数器的 Time.sleep 不准确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30075344/