gpt4 book ai didi

python - Python 3.x 和 Windows 7 的 time.sleep() 不准确

转载 作者:行者123 更新时间:2023-12-01 03:01:38 24 4
gpt4 key购买 nike

this之后这篇文章中,我发现了 Windows 7(企业版、64 位和 Python 3.4.4)下 Python time.sleep() 函数的非功能性实现。

这是引用 .py 脚本:

import threading, time

def Return():
return

def Setup():
for _ in range(10):
time_before = time.time()
Return()
wait_delay = -time.time()

delays = []
InputFrequency = 60

while (time.time() - time_before) < (1 / InputFrequency):
time.sleep(0)

wait_delay += time.time()

delays.append(wait_delay)

print("Output frequency: " + str([1/t for t in delays][0]) + " Hz")

threading.Thread(target=Setup).start()

根据this例如,此脚本应产生大约 60Hz 的输出频率。但是,当在我的 Windows 7 Enterprise 计算机上运行时,这些是我在给定输入频率下收到的输出频率:

输入:10Hz - 输出:9.15Hz

<小时/>

输入:20Hz - 输出:16.03Hz

<小时/>

输入:30Hz - 输出 21.37Hz

<小时/>

输入范围:40Hz - 64Hz - 输出:32.05Hz

<小时/>

输入范围:65Hz - 10kHz+ - 输出:64.10Hz

<小时/>

这是怎么回事?为什么不同的输入频率(40Hz 以上)会产生相同的输出频率?为什么输入频率超过10000Hz,输出频率上限还是64.10Hz?我不认为这是 ~60Hz 的 time.sleep() 分辨率问题。提供给 ideone.com 脚本的相同输入频率值会产生预期的输出频率,因此它必须与我的计算机相关。

最佳答案

Python 对这些调用的行为方式几乎没有保证,尤其是跨平台。这里有两件事可能会出现问题 - time.time() 的分辨率比您尝试实现的分辨率更差,或者 sleep 的分辨率更差。

在最近的平台上, sleep 应该大约至少有 1 到 2 毫秒的准确度,如下所示:

How accurate is python's time.sleep()?

剩下time.time()。此特定调用的文档警告准确性可能较差:

Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

幸运的是,time.perf_counter() 中提供了更高分辨率的时钟 API,它尝试访问平台上可用的最高分辨率时钟。来自文档:

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

对于 Windows,这似乎比 60Hz 更好,这可以解决您的问题。

关于python - Python 3.x 和 Windows 7 的 time.sleep() 不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43772960/

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