在Python中通过Windows核心API获取高精度计时

为了获取微秒级的高精度计时,可以调用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())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值