我想用Python编写自己的时钟对象。我希望它非常非常准确。我在Windows上看到,我可以使用QueryPerformanceCounter()。但是怎么样?我不知道任何C;只有Python 2.x.
有人可以给我一个提示,告诉我如何在Python中使用它来在Win上制作一个准确的时钟吗?
答案 0 :(得分:5)
我使用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)
希望这有帮助!