Python 2.x-Windows上的QueryPerformanceCounter()

Python 2.x-Windows上的QueryPerformanceCounter(),python,windows,time,clock,performancecounter,Python,Windows,Time,Clock,Performancecounter,我想用Python编程我自己的时钟对象。我希望它非常非常准确。我在Windows上读到,我可以使用QueryPerformanceCounter()。但是怎么做呢?我不知道任何C;只有Python2.x 有人能给我一个提示,告诉我如何在Python中使用它来制作Win上的精确时钟吗?我已经使用ctypes模块移植了您提供给Python的: C++ LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds; LARGE_INTEGER

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

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

我已经使用
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所评论的,您也可以使用,它是用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)

希望这有帮助

哪里是
QueryPerformanceCounter()
?Windows API?是-见,谢谢。我现在正在做一些测试,我相信我有一个解决方案,在一些缺点。继续看:)太好了,谢谢!好的,我现在想起来了。我不完全理解的是函数的用法,它(写在文档中)失败时只返回零,成功时不返回零。你知道这方面的情况吗?非常感谢你的努力,但是我想如果不学习C语言我就做不到。我不知道C类型,所以我无法修复您提供的解决方法。如果你有时在附近,如果我有更多的想法,我可以向你发表评论。我刚刚发现这些c_longlong_Array_1对象是可移植的,obj[0]是我认为的时间值:在Windows上尝试“ElapsedMicroseconds=EndingTime[0]-StartingTime[0]”,是通过和。避免
windell
。其他一些基于ctypes的库可能会在同一脚本中使用,但它们的定义是
restype
argtypes
、和
errcheck
,这会破坏您的代码。而是使用
kernel32=ctypes.windell('kernel32',使用\u last\u error=True)
。在支持Windows上次错误值的函数上设置
errcheck
属性(参见文档),您可以通过
ctypes安全地获取该值。获取上次错误()
并通过
ctypes.WinError(code)
获取异常。对Windows数据类型使用
ctypes.wintypes
,例如
st=wintypes.LARGE_INTEGER()
kernel32.QueryPerformanceCounter(ctypes.byref(st))