在python中睡眠确切时间 [英] Sleep for exact time in python

查看:53
本文介绍了在python中睡眠确切时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的一项功能中等待大约 25 毫秒.有时,当处理器被其他事情占用时调用此函数,有时它会独占处理器.

I need to wait for about 25ms in one of my functions. Sometimes this function is called when the processor is occupied with other things and other times it has the processor all to itself.

我尝试过 time.sleep(.25) 但有时实际上是 25 毫秒,而其他时候则需要更长的时间.无论处理器可用性如何,有没有一种方法可以在确切的时间内休眠?

I've tried time.sleep(.25) but sometimes its actually 25ms and other times it takes much longer. Is there a way to sleep for an exact amount of time regardless of processor availability?

推荐答案

因为您正在使用 抢占式 操作系统,您无法保证您的进程能够在 25 毫秒内控制 CPU.

Because you're working with a preemptive operating system, there's no way you can guarantee that your process will be able to have control of the CPU in 25ms.

如果您仍然想尝试,最好有一个繁忙的循环,轮询直到 25 毫秒过去.像这样的事情可能会奏效:

If you'd still like to try, it would be better to have a busy loop that polls until 25ms has passed. Something like this might work:

import time
target_time = time.clock() + 0.025
while time.clock() < target_time:
    pass

这篇关于在python中睡眠确切时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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