C++ 跨平台高分辨率定时器

2021-12-31 00:00:00 timer cross-platform 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_timemicrosec_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.它的 性能库 有几个类可以满足您的需求.(要使其跨平台,请选择一个在 winstlunixstl 命名空间中都存在的类似 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.

相关文章