Python 2.x - Windows 上的 QueryPerformanceCounter()

Python 2.x - QueryPerformanceCounter() on Windows

我想使用 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)

希望对您有所帮助!