Skip to main content
 首页 » 编程设计

python之与 sleep 命令相比,使用循环在 python 中等待更多 CPU 密集型

2025年05月04日13JustinYoung

在 python 3 上,我需要停止直到某个时间。而且我需要非常准确地知道我什么时候醒来。问题是在这个暂停期间我应该做一些计算,这将占用这段时间。所以我不能只是 time.sleep() 通过它,否则我会开始得太晚。

所以我在考虑运行这段代码:

import time 
wakeuptime=time.time()+20 #start again exactly 20 seconds from now 
UnpredictablySlowFunction()   
while (time.time()<wakeuptime):  
    pass 

我有点担心这种循环可能比普通的 time.sleep() 更无用地占用 CPU。特别是考虑到该程序应在后台 24/7 全天候运行。

请您参考如下方法:

正如@tobias_k 在评论中提到的,试试这个:

import time 
wakeuptime=time.time()+20 #start again exactly 20 seconds from now 
UnpredictablySlowFunction()   
time_left = wakeuptime -time.time() 
time.sleep(time_left)