Python 计数器的 Time.sleep 不准确? [英] Time.sleep inaccurate for Python counter?

查看:144
本文介绍了Python 计数器的 Time.sleep 不准确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为工作中的销售团队创建一个收入计数器,并且喜欢使用 Python.例如.Joe Bloggs 将他的目标从 22.1 转移到 23.1(差异为 1.0).我希望计数器在一个小时内从 22.1 均匀地跳动到 23.1.

I'd like to create a revenue counter for the sales team at work and would love to use Python. E.g. Joe Bloggs shifts his target from 22.1 to 23.1 (difference of 1.0.) I'd like the counter to tick evenly from 22.1 to 23.1 over an hour.

我创建了这个脚本,它可以很好地计算一分钟(每分钟运行 2 秒);然而,当它应该运行一个小时时,它运行了 47 分钟.

I've created this script, which works fine for counting a minute (runs 2 seconds over the minute); however, when it's supposed to run for an hour, it runs for 47 minutes.

问题:有谁知道为什么当我将它设置为一小时时它运行得更快?sleep.time 不准确吗?

Question: Does anyone know why it runs faster when I set it to an hour? Is sleep.time inaccurate?

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

推荐答案

请注意 Python 文档中关于 time.sleep()

Please note this quote from the Python documentation for time.sleep()

实际暂停时间可能比要求的要少,因为任何执行该信号后,捕获的信号将终止 sleep()信号的捕捉例程.另外,暂停时间可能会更长比由于安排的任意数量要求系统中的其他活动.

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 醒来时,检查是否已经过了预期的时间.如果不是,则重新启动睡眠以获取差异等

As a suggestion, if faced with this problem, I would use a variable to track the time that the interval starts. When sleep wakes up, check to see if the expected time has elapsed. If not, restart a sleep for the difference, etc.

这篇关于Python 计数器的 Time.sleep 不准确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆