python - Python 计数器的 Time.sleep 不准确?

标签 python python-2.7 time sleep

我想为工作中的销售团队创建一个收入计数器,并且喜欢使用 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/

相关文章:

python - openCV模板匹配错误: (-215)

python : Set method attribute from within method

python - 如何存储相同的参数以供多个函数使用

iOS 时间戳计算

PHP/MySQL - 将日期时间显示为日期

python - `try... except Exception as e` 是否捕获所有可能的异常?

python - 为什么冒泡排序时数组的最小元素没有排序?

python - 没有括号打印不起作用(Python 2.7)

python - 找到几个单词,如果删除一个字母将打印出这两个单词

linux - 将 bash 脚本中的时间与 ± x 分钟进行比较