python 中time.sleep() 的极限

windows下time.sleep(0.001) 会耗时15ms,最小精确到15ms

ubuntu下time.sleep(0.001)会耗时1ms,最小可精确到0.1ms

windows下解决办法:

QueryPerformanceFrequency是操作系统的性能统计分辨率,也就是每秒钟统计多少次的意思。

QueryPerformanceCounter 是系统性能统计计数器,表示统计了多少次,除以QueryPerformanceFrequency,得到系统运行时间(秒数)。

QueryPerformanceCounter2-QueryPerformanceCounter1,得到高精度(微秒级,=1/QueryPerformanceFrequency秒)的时间差,常用于winddows高精度计时。

QueryPerformanceFrequency() -基本介绍

类型:Win32API

原型:BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency);

作用:返回硬件支持的高精度计数器的频率。

返回值:非零,硬件支持高精度计数器;零,硬件不支持,读取失败。

 

#!/usr/bin/python3
# -*- coding: utf-8 -*-

# 提供了与 C 兼容的数据类型,并允许调用 DLL 或共享库中的函数
import ctypes


class Timer(object):

    def __init__(self):
        freq = ctypes.c_longlong(0)
        ctypes.windll.kernel32.QueryPerformanceFrequency(ctypes.byref(freq))
        self.__freq = freq.value
        self.__beginCount = self.counter()

    def counter(self):
        freq = ctypes.c_longlong(0)
        ctypes.windll.kernel32.QueryPerformanceCounter(ctypes.byref(freq))
        return freq.value

    def beginCount(self):
        self.__beginCount = self.counter()

    # 时间差,精确到微秒
    def secondsDiff(self):
        self.__endCount = self.counter()
        return (self.__endCount - self.__beginCount) / (self.__freq + 0.)

    # 休眠,精确到毫秒
    def sleep(self, timeout):
        while True:
            self.__endCount = self.counter()
            if ((self.__endCount - self.__beginCount) / (self.__freq + 0.)) * 1000 >= timeout:
                return

 

posted @ 2023-01-10 19:18  小柴i  阅读(1497)  评论(0编辑  收藏  举报