为了获取微秒级的高精度计时,可以调用windows操作系统提供的API来这现。基本原理是通过QueryPerformanceFrequency()获取cpu频率;通过QueryPerformanceCounter()获取每秒的计数值,用计数值之差除以频率就可以得到流逝的时间。
为了调用的方便,将该功能封装成了class。
文件 timer.py放置于目录highPrecTimer之下,该目录下还放置了一个空文件__init__.py,于是该目录成为了一个python模块。
timer.py的内容如下
# -*- coding:utf-8 -*-
# 用于提供较高精度的时间差,根据文献,精度可达微秒级
import time,ctypes
import datetime
#提供类方法,获取时间差
class SingleTimer(object):
__freq =None
__beginCount=0
__endCount =0
@classmethod
def counter(cls):
freq = ctypes.c_longlong(0)
ctypes.windll.kernel32.QueryPerformanceCounter(ctypes.byref(freq))
return freq.value
@classmethod
def beginCount(cls):
freq = ctypes.c_longlong(0)
ctypes.windll.kernel32.QueryPerformanceFrequency(ctypes.byref(freq))
cls.__freq=freq.value
cls.__beginCount = cls.counter()
#时间差,精确到微秒
@classmethod
def secondsDiff(cls):
cls.__endCount = cls.counter()
return (cls.__endCount-cls.__beginCount)/(cls.__freq+0.)
#提供实例方法,获取时间差
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.)
测试函数所在的文件
test.py
# -*- coding:utf-8 -*-
# 测试用代码
import time
from highPrecTimer.timer import Timer as HpTimer
t = HpTimer()
time.sleep(1)
print(t.secondsDiff())