系统相关
首页 > 系统相关> > Python 2.x – Windows上的QueryPerformanceCounter()

Python 2.x – Windows上的QueryPerformanceCounter()

作者:互联网

我想用Python编写自己的时钟对象.我希望它非常非常准确.我在Windows上看到,我可以使用QueryPerformanceCounter().但是怎么样?我不知道任何C;只有Python 2.x.

有人能给我一个提示,告诉我如何在Python中使用它来在Win上制作一个准确的时钟吗?

解决方法:

我使用ctypes模块移植了你给Python的C++ example

C

LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds;
LARGE_INTEGER Frequency;

QueryPerformanceFrequency(&Frequency); 
QueryPerformanceCounter(&StartingTime);

// Activity to be timed

QueryPerformanceCounter(&EndingTime);
ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart;

ElapsedMicroseconds.QuadPart *= 1000000;
ElapsedMicroseconds.QuadPart /= Frequency.QuadPart;

Python

import ctypes
import ctypes.wintypes
import time

kernel32             = ctypes.WinDLL('kernel32', use_last_error=True)

starting_time        = ctypes.wintypes.LARGE_INTEGER()
ending_time          = ctypes.wintypes.LARGE_INTEGER()
elapsed_microseconds = ctypes.wintypes.LARGE_INTEGER()
frequency            = ctypes.wintypes.LARGE_INTEGER()

kernel32.QueryPerformanceFrequency(ctypes.byref(frequency)) 
kernel32.QueryPerformanceCounter(ctypes.byref(starting_time))

# Activity to be timed, e.g.
time.sleep(2)

kernel32.QueryPerformanceCounter(ctypes.byref(ending_time))

elapsed_microseconds = ending_time.value - starting_time.value
elapsed_microseconds *= 1000000
elapsed_microseconds /= frequency.value

print(elapsed_microseconds)

我真的很感激@eryksun的有用提示!

上面的代码应该打印接近2000000的东西(例如2000248.7442040185,该值可能不时地不同).您也可以使用round()或int()函数来除去小数.

正如@eryksun所评论的那样,您也可以使用time.clock(),它在C中实现,并且还使用QueryPerformanceCounter().

与使用ctypes完全相同的示例:

import time
starting_time = time.clock()

# Activity to be timed, e.g.
time.sleep(2)

ending_time = time.clock()

elapsed_microseconds = ending_time - starting_time
elapsed_microseconds *= 1000000

print(elapsed_microseconds)

希望这可以帮助!

标签:python,windows,time,clock,performancecounter
来源: https://codeday.me/bug/20190608/1199667.html