2011-04-06 241 views

回答

30

由于usleep通常意味着希望延迟对于x微秒执行,则必须通过1000000

import time 
time.sleep(seconds/1000000.0) 

time.sleep()只需几秒钟作为参数划分秒值。

http://docs.python.org/library/time.html#time.sleep

+7

仔细阅读[睡眠准确度()](http://stackoverflow.com/questions/1133857/how-accurate-is-pythons-time-sleep) – x29a 2015-07-18 12:27:17

2
from time import sleep 
sleep(seconds) 

More info

6
from time import sleep 
sleep(0.1) #sleep during 100ms 
20
import time 
usleep = lambda x: time.sleep(x/1000000.0) 

usleep(100) #sleep during 100μs 
2

非常非常小心time.sleep。我被python3使用time.sleep烧了,因为它是非单调的。如果挂钟倒退,time.sleep呼叫将不会完成,直到挂钟赶上睡眠按计划前进的位置。我还没有发现蟒蛇单调睡眠。

相反,我建议Event.wait,像这样:

def call_repeatedly(interval, func, *args, **kwargs): 
    stopped = Event() 
    def loop(): 
     while not stopped.wait(interval): # the first call is in `interval` secs 
      try: 
       func(*args) 
      except Exception as e: 
       logger.error(e); 
       if kwargs.get('exception'): 
        kwargs.get('exception')(e) # SEND exception to the specified function if there is one. 
       else: 
        raise Exception(e) 
    Thread(target=loop).start() 
    return stopped.set 

http://pastebin.com/0rZdY8gB

+0

介意添加代码? – manetsus 2015-12-19 02:17:25

+0

当然,我很乐意:[http://pastebin.com/0rZdY8gB](http://pastebin.com/0rZdY8gB) – SynaTree 2016-02-06 05:29:44

+0

我相信'time.sleep'现在应该在Python 3中是单调的;至少,[源代码](https://github.com/python/cpython/blob/v3.6.3/Modules/timemodule.c#L1430)说'_PyTime_GetMonotonicClock()'获取当前时间。我无法确定过去的行为是什么样的。 – user2357112 2017-10-26 00:16:51

-3

这个怎么样:

import time 
def usleep(delay): 
    mdelay = delay /1000 
    now = time.time() 
    while now + mdelay > time.time(): 
     pass 
+0

你消耗100%的CPU,直到延迟结束?这是开发人员在MSDOS时代所做的,请不要在现代多任务系统上这样做。用'time.sleep()'告诉OS内核让你的进程暂停,直到超时完成,所有其他进程可以完成他们的工作。 – vdboor 2016-10-25 08:56:42

+0

这可能会消耗100%的CPU,但至少比睡眠准确得多。如果你必须睡很多才能保持时间,例如当在一个Rapsberry Pi上绑定一个协议time.sleep()有时是WAY的(我正在谈论一个因子20!) – Dakkaron 2016-11-02 14:19:25

+1

通过保持CPU 100%加载,实际上可以减慢时钟,如果你的clocksource受系统负载和下降的电压...忍受这一点,你会失去不仅仅是睡觉精度 – Andrew 2016-11-10 20:39:40

1

的蟒蛇是交替睡眠功能。

注意:由于GIL锁,不应该用于多线程,但对于多个子进程来说它很好。与time.sleep()相同

我正在将C函数封装到Python中。我正在使用C库的nanosleep()函数,这会暂停运行那么多时间的线程。这不是一个忙碌的等待类型的延迟,它使用很多CPU来评估一些数学。代码如下。 CWrapper说,把所有的文件放在一个文件夹中。

C_functions.h

#include <time.h> 
int c_sleep_msec(long milliseconds); 
int c_sleep_nsec(long nanoseconds); 

C_functions.c

#include "C_functions.h" 
int c_sleep_msec(long milliseconds) { 
    struct timespec req; 
    //struct timespec rem; 
    if(milliseconds > 999) { 
     req.tv_sec = (int)(milliseconds/1000); /* Must be Non-Negative */ 
     req.tv_nsec = (milliseconds - ((long)req.tv_sec * 1000)) * 1000000; /* Must be in range of 0 to 999999999 */ 
    } 
    else { 
     req.tv_sec = 0;       /* Must be Non-Negative */ 
     req.tv_nsec = milliseconds * 1000000; /* Must be in range of 0 to 999999999 */ 
    } 
    //rem = NULL; 
    return nanosleep(&req , NULL); 
} 
//------------------------------------------------------ 
int c_sleep_nsec(long nanoseconds) { 
    struct timespec req; 
    //struct timespec rem; 
    if (nanoseconds > 999999999) { 
     req.tv_sec = (int)(nanoseconds/1000000000); 
     req.tv_nsec = (nanoseconds - ((long)req.tv_sec * 1000000000)); 
    } 
    else { 
     req.tv_sec = 0; 
     req.tv_nsec = nanoseconds; 
    } 
    //rem = NULL; 
    return nanosleep(&req , NULL); 
} 

还可以创建使用相同了nanosleep()

CWrapper.pyx

cdef extern from "C_functions.h": 
    int c_sleep_msec(long milliseconds) 
    int c_sleep_nsec(long nanoseconds) 

def sleep_msec(milliseconds): 
    return c_sleep_msec(milliseconds) 

def sleep_nsec(nanoseconds): 
    return c_sleep_nsec(nanoseconds) 
微秒的功能

setup.py

from distutils.core import setup 
from distutils.extension import Extension 
from Pyrex.Distutils import build_ext 

setup(
    name = "CWrapper", 
    ext_modules=[ Extension("CWrapper", ["CWrapper.pyx", "C_functions.c"]) ], 
    cmdclass = {'build_ext': build_ext} 
) 

安装python-pyrex。然后在linux终端上运行

python setup.py build_ext -i 

它会创建CWrapper.c,build和CWrapper.so文件。使用CWrapper.so只要你想要的,只需在python中导入。

注意:分别为Raspberry Pi编译。

现在,测试函数

Test_sleep.py

import serial 
from multiprocessing import Process 
import time 
import CWrapper 


class TestSleep: 
    def __init__(self): 
     self.delay_sec = 0.00000100 
     self.delay_msec = 30 
     self.delay_nsec = 1000 #200000000 
     self.start_time = time.time() 

     self.process_1 = Process(name="process_1", target=self.process_1_task, args=("process_1",)) 
     self.process_1.daemon = True 
     self.process_1.start() 

     self.process_2 = Process(name="process_2", target=self.process_1_task, args=("process_2",)) 
     self.process_2.daemon = True 
     self.process_2.start() 

     self.process_3 = Process(name="process_3", target=self.process_1_task, args=("process_3",)) 
     self.process_3.daemon = True 
     self.process_3.start() 

    def process_1_task(self, process_name): 
     start = self.start_time 
     delay_msec = self.delay_msec 
     delay_sec = self.delay_sec 
     delay_nsec = self.delay_nsec 

     t1 = start 
     for i in range(1, 81): 
      status = CWrapper.sleep_msec(delay_msec) 
      # status = CWrapper.sleep_nsec(delay_nsec) 
      #status = time.sleep(delay_sec) 
      t2 = time.time() 
      elapsed_time = t2 - t1 
      t1 = t2 
      print process_name, i, "status:", status, "Elapsed-time:", elapsed_time 


if __name__ == '__main__': 
    test = TestSleep() 
    # for i in range(1,10000): 
    #  print "main thread", i 
     # time.sleep(0.1) 
    while True: # Since daemon=True, main thread should check join() or stay in loop 
     pass 

改变参数delay_sec为time.sleep(),用于delay_msec CWrapper.sleep_msec(),用于delay_nsec CWrapper.sleep_nsec()。取消您想要在thread_1_task()中测试的函数的注释。

+0

所以这是你复制这篇文章的地方?你的例子仍然在滥用线程(无论是忙于旋转还是阻止它们运行),所以比较不能保持。在解决一个已知问题时,请将其定义为“不适当”。 – 2017-06-22 08:05:02

+0

至于你的证明,忙碌的等待并不是睡眠,它仍然是你的主线;您编写的例程只停止*全部* Python线程。 – 2017-06-22 08:10:54

+0

请阅读http://docs.cython.org/en/latest/src/userguide/external_C_code.html#acquiring-and-releasing-the-gil – 2017-06-22 08:16:07