Python 2.x – Windows上的QueryPerformanceCounter()
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python 2.x – Windows上的QueryPerformanceCounter(),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1914字,纯文字阅读大概需要3分钟。
内容图文
![Python 2.x – Windows上的QueryPerformanceCounter()](/upload/InfoBanner/zyjiaocheng/969/c71afc21369c4481b0255d7404c675ba.jpg)
我想用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)
希望这可以帮助!
内容总结
以上是互联网集市为您收集整理的Python 2.x – Windows上的QueryPerformanceCounter()全部内容,希望文章能够帮你解决Python 2.x – Windows上的QueryPerformanceCounter()所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。