Python 2.x - Windows

时间:2016-07-20 17:31:38

标签: python windows time sleep clock

我在这个论坛上得到了一些关于如何在Python 2中编写时钟对象的一些非常好的提示。我现在已经有了一些代码。这是一个“嘀嗒”的时钟。在60 FPS:

import sys
import time

class Clock(object):

    def __init__(self):

        self.init_os()
        self.fps = 60.0
        self._tick = 1.0 / self.fps
        print "TICK", self._tick
        self.check_min_sleep()
        self.t = self.timestamp()

    def init_os(self):

        if sys.platform == "win32":
            self.timestamp = time.clock
            self.wait = time.sleep

    def timeit(self, f, args):

        t1 = self.timestamp()
        f(*args)
        t2 = self.timestamp()
        return t2 - t1

    def check_min_sleep(self):
        """checks the min sleep time on the system"""

        runs =  1000
        times = [self.timeit(self.wait, (0.001, )) for n in xrange(runs)]
        average = sum(times) / runs
        print "average min sleep time:", round(average, 6)
        sort = sorted(times)
        print "fastest, slowest", sort[0], sort[-1]

    def tick(self):

        next_tick = self.t + self._tick
        t = self.timestamp()
        while t < next_tick:
            t = self.timestamp()
        self.t = t

if __name__ == "__main__":
    clock = Clock()

时钟不会太糟糕,但为了避免繁忙的循环,我希望Windows睡眠时间少于平常约15毫秒。在我的系统(64位Windows 10)上,如果Python是唯一正在运行的应用程序,它在启动时钟时平均返回大约15/16毫秒。为了避免繁忙的循环,这对于最小睡眠来说太长了。

有人知道如何让Windows睡眠时间低于该值吗?

1 个答案:

答案 0 :(得分:3)

您可以暂时将计时器时间段降低到timeGetDevCaps返回的wPeriodMin值。以下定义了timer_resolution上下文管理器,用于调用timeBeginPeriodtimeEndPeriod函数。

import timeit
import contextlib
import ctypes
from ctypes import wintypes

winmm = ctypes.WinDLL('winmm')

class TIMECAPS(ctypes.Structure):
    _fields_ = (('wPeriodMin', wintypes.UINT),
                ('wPeriodMax', wintypes.UINT))

def _check_time_err(err, func, args):
    if err:
        raise WindowsError('%s error %d' % (func.__name__, err))
    return args

winmm.timeGetDevCaps.errcheck = _check_time_err
winmm.timeBeginPeriod.errcheck = _check_time_err
winmm.timeEndPeriod.errcheck = _check_time_err

@contextlib.contextmanager
def timer_resolution(msecs=0):
    caps = TIMECAPS()
    winmm.timeGetDevCaps(ctypes.byref(caps), ctypes.sizeof(caps))
    msecs = min(max(msecs, caps.wPeriodMin), caps.wPeriodMax)
    winmm.timeBeginPeriod(msecs)
    yield
    winmm.timeEndPeriod(msecs)

def min_sleep():
    setup = 'import time'
    stmt = 'time.sleep(0.001)'
    return timeit.timeit(stmt, setup, number=1000)

实施例

>>> min_sleep()
15.6137827

>>> with timer_resolution(msecs=1): min_sleep()
...
1.2827173000000016

原始计时器分辨率在with阻止后恢复:

>>> min_sleep()
15.6229814