Python 2.x - Windows上的QueryPerformanceCounter()

Don*_*one 4 python windows time clock performancecounter

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

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

lin*_*usg 5

我已经使用模块移植了你给Python 的C++示例ctypes:

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;
Run Code Online (Sandbox Code Playgroud)

蟒蛇

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)
Run Code Online (Sandbox Code Playgroud)

我真的很感激@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)
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 在 Windows 上,[`time.clock`](https://docs.python.org/2/library/time.html#time.clock) 已[实现](https://hg.python.org/cpython/ file/v2.7.12/Modules/timemodule.c#l162) 通过 [`QueryPerformanceCounter`](https://msdn.microsoft.com/en-us/library/ms644904) 和 [`QueryPerformanceFrequency`](https:// msdn.microsoft.com/en-us/library/ms644905)。 (2认同)