我期待在C ++中实现一个简单的计时器机制。该代码应该在Windows和Linux中运行。分辨率应尽可能精确。这将用于简单追踪时间的流逝,而不是实施任何事件驱动的设计。什么是实现这一目标的最佳工具?
发布于 2018-04-18 16:51:24
Boost.Date_Time包含之前在Stack Overflow上推荐的ptime
类。看到它的文档上microsec_clock::local_time
和microsec_clock::universal_time
,但要注意它告诫说,“Win32系统往往不通过这个API达到微秒级的分辨率。”
STLsoft提供了针对操作系统特定API的精简跨平台(Windows和Linux / Unix)C ++包装。它的性能库有几个可以做你需要的类。(为了让跨平台,挑一类就像performance_counter
在两个存在winstl
和unixstl
命名空间,然后使用哪个命名空间平台相匹配。)
发布于 2018-04-18 17:59:08
你可以通过以下方式轻松地获得最高分辨率的计时器:
#include <iostream>
#include <chrono>
#include "chrono_io"
int main()
{
typedef std::chrono::high_resolution_clock Clock;
auto t1 = Clock::now();
auto t2 = Clock::now();
std::cout << t2-t1 << '\n';
}
示例输出:
74 nanoseconds
这是对Ben下面的评论的回应,随后的调用std::chrono::high_resolution_clock
在VS11中需要几个毫秒。以下是一个<chrono>
兼容的解决方法。然而,它只适用于英特尔硬件,您需要深入内联汇编(根据编译器的不同语法),并且必须将机器的时钟速度硬连线到时钟:
#include <chrono>
struct clock
{
typedef unsigned long long rep;
typedef std::ratio<1, 2800000000> period; // My machine is 2.8 GHz
typedef std::chrono::duration<rep, period> duration;
typedef std::chrono::time_point<clock> time_point;
static const bool is_steady = true;
static time_point now() noexcept
{
unsigned lo, hi;
asm volatile("rdtsc" : "=a" (lo), "=d" (hi));
return time_point(duration(static_cast<rep>(hi) << 32 | lo));
}
private:
static
unsigned
get_clock_speed()
{
int mib[] = {CTL_HW, HW_CPU_FREQ};
const std::size_t namelen = sizeof(mib)/sizeof(mib[0]);
unsigned freq;
size_t freq_len = sizeof(freq);
if (sysctl(mib, namelen, &freq, &freq_len, nullptr, 0) != 0)
return 0;
return freq;
}
static
bool
check_invariants()
{
static_assert(1 == period::num, "period must be 1/freq");
assert(get_clock_speed() == period::den);
static_assert(std::is_same<rep, duration::rep>::value,
"rep and duration::rep must be the same type");
static_assert(std::is_same<period, duration::period>::value,
"period and duration::period must be the same type");
static_assert(std::is_same<duration, time_point::duration>::value,
"duration and time_point::duration must be the same type");
return true;
}
static const bool invariants;
};
const bool clock::invariants = clock::check_invariants();
这个时钟的持续时间取决于你的CPU时钟速度(正如你所报告的那样)。即对我来说,这个时钟每秒钟1 / 2,800,000,000次滴答一次。如果你愿意,你可以将它转换为纳秒:
using std::chrono::nanoseconds;
using std::chrono::duration_cast;
auto t0 = clock::now();
auto t1 = clock::now();
nanoseconds ns = duration_cast<nanoseconds>(t1-t0);
https://stackoverflow.com/questions/-100003922
复制相似问题