在Python中使用usleep

时间:2011-04-06 15:08:58

标签: python

我在Python 2.7中搜索usleep()函数。

有人知道它是否存在,可能还有另一个函数名吗?

8 个答案:

答案 0 :(得分:41)

由于usleep通常意味着您希望延迟执行x微秒,因此必须将秒值除以1000000。

import time
time.sleep(seconds/1000000.0)

time.sleep()需要几秒作为参数。

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

答案 1 :(得分:25)

import time
usleep = lambda x: time.sleep(x/1000000.0)

usleep(100) #sleep during 100μs

答案 2 :(得分:6)

from time import sleep
sleep(0.1) #sleep during 100ms

答案 3 :(得分:5)

三行代码称为“原始”睡眠:

Widget buildBackButton() {
    double size = 47;
    return Stack(
      children: <Widget>[
        Container(
          width: size,
          height: size,
          decoration: BoxDecoration(
              color: Colors.white,
              shape: BoxShape.circle,
              boxShadow: [
                BoxShadow(
                  color: Colors.black26,
                  offset: Offset(20, 20),
                  blurRadius: 40,
                ),
                BoxShadow(
                  color: Colors.white,
                  offset: Offset(-20, -20),
                  blurRadius: 25,
                )
              ]),
          child: Material(
            color: Color(0xffe0eafb),
            borderRadius: BorderRadius.circular(size),
            elevation: 10,
            child: Padding(
              padding: const EdgeInsets.all(3.0),
              child: ClipOval(
                clipper: MClipper(),
              ),
            ),
          ),
        ),
        Container(
            width: 45.0,
            height: 45.0,
            padding: EdgeInsets.only(left: 2, top: 2),
            child: new RawMaterialButton(
              shape: new CircleBorder(),
              fillColor: Color(0xffe0eafb),
              elevation: 10.0,
              child: Icon(
                Icons.arrow_back,
                color: Colors.black,
              ),
              onPressed: () {},
            )),
      ],
    );
  }

class MClipper extends CustomClipper<Rect> {
  @override
  Rect getClip(Size size) {
    return Rect.fromCircle(
        center: Offset(size.width / 2, size.height / 2),
        radius: min(size.width, size.height) / 2);
  }

  @override
  bool shouldReclip(CustomClipper<Rect> oldClipper) {
    return true;
  }
}

在centos和alpine上都对python 3.8.1进行了测试

答案 4 :(得分:4)

对time.sleep要非常小心。我使用time.sleep被python3烧毁,因为它是非单调的。如果挂钟向后变化,则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

答案 5 :(得分:2)

from time import sleep
sleep(seconds)

More info

答案 6 :(得分:1)

python的备用休眠函数。

注意:由于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

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

答案 7 :(得分:-3)

怎么样:

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