C++ Cross-Platform High-Resolution Timer(C++ 跨平台高分辨率定时器)
问题描述
我希望在 C++ 中实现一个简单的计时器机制.该代码应该适用于 Windows 和 Linux.分辨率应尽可能精确(至少毫秒精度).这将用于简单地跟踪时间的流逝,而不是实现任何类型的事件驱动设计.实现这一目标的最佳工具是什么?
I'm looking to implement a simple timer mechanism in C++. The code should work in Windows and Linux. The resolution should be as precise as possible (at least millisecond accuracy). This will be used to simply track the passage of time, not to implement any kind of event-driven design. What is the best tool to accomplish this?
推荐答案
对于 C++03:
Boost.Timer 可能有用,但它取决于 C 函数 clock,因此可能没有足够好的分辨率.
Boost.Timer might work, but it depends on the C function clock and so may not have good enough resolution for you.
Boost.Date_Time 包括一个 ptime class 之前在 Stack Overflow 上被推荐过.请参阅其关于 microsec_clock::local_time 和 microsec_clock::universal_time 的文档,但请注意其警告Win32 系统通常无法通过此 API 实现微秒分辨率."
Boost.Date_Time includes a ptime class that's been recommended on Stack Overflow before. See its docs on microsec_clock::local_time and microsec_clock::universal_time, but note its caveat that "Win32 systems often do not achieve microsecond resolution via this API."
STLsoft 提供了围绕 OS 的瘦跨平台(Windows 和 Linux/Unix)C++ 包装器等.特定的 API.它的 性能库 有几个类可以满足您的需求.(要使其跨平台,请选择一个在 winstl 和 unixstl 命名空间中都存在的类似 performance_counter 的类,然后使用与您的平台匹配的命名空间.)
STLsoft provides, among other things, thin cross-platform (Windows and Linux/Unix) C++ wrappers around OS-specific APIs. Its performance library has several classes that would do what you need. (To make it cross platform, pick a class like performance_counter that exists in both the winstl and unixstl namespaces, then use whichever namespace matches your platform.)
对于 C++11 及更高版本:
std::chrono 库内置了此功能.请参阅此答案@HowardHinnant 了解详情.
The std::chrono library has this functionality built in. See this answer by @HowardHinnant for details.
这篇关于C++ 跨平台高分辨率定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 跨平台高分辨率定时器
基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
