Python:高精度的time.sleep

2024-03-29 15:03:48 发布

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


Tags: python
3条回答

可以在^{}中使用浮点数:

The argument may be a floating point number to indicate a more precise sleep time.

所以

time.sleep(0.5)

会睡半秒钟。

然而,在实践中,睡眠的精确度不可能超过毫秒,因为操作系统通常只支持毫秒睡眠,而且很短的时间很快就会变得不可靠。

def start(self):
    sec_arg = 10.0
    cptr = 0
    time_start = time.time()
    time_init = time.time()
    while True:
        cptr += 1
        time_start = time.time()
        time.sleep(((time_init + (sec_arg * cptr)) - time_start ))

        # AND YOUR CODE .......
        t00 = threading.Thread(name='thread_request', target=self.send_request, args=([]))
        t00.start()

在linux上它的精确度非常好

下面是一个类似的问题:

how-accurate-is-pythons-time-sleep

在linux上,如果您需要高精度,您可能需要使用ctypes来调用nanosleep()clock_nanosleep()。不过,我不确定这么做会有什么影响。

相关问题 更多 >