gpt4 book ai didi

Python 2.x - Windows 上的 QueryPerformanceCounter()

转载 作者:可可西里 更新时间:2023-11-01 14:02:36 25 4
gpt4 key购买 nike

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

谁能告诉我如何在 Python 中使用它在 Win 上制作准确的时钟?

最佳答案

我移植了 C++ example您已经使用 ctypes 模块提供给 Python:

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 2.x - Windows 上的 QueryPerformanceCounter(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38461335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com