![](/img/trans.png)
[英]odd behaviour using chrono::high_resolution_clock::now()
[英]how to use chrono::high_resolution_clock::now() in threads
我在函数中使用chrono::high_resolution_clock::now()
来确定一个循环需要多长时间才能获得x重复次数的估计完成时间。 然而,从使用主调用时future
,它给出的时间是错误的。 我使用过Visual C ++和Intel C编译器。 如何解决呢?
这是VC和其他应用程序中的一个已知错误 ,标头使用的系统时钟不是很高的分辨率。 如果您想要真正准确的计时,请使用boost或rdtsc。
使用boost可以像使用std :: chrono一样使用它,该示例来自链接:
boost::chrono::high_resolution_clock::time_point t3 = boost::chrono::high_resolution_clock::now();
boost::chrono::high_resolution_clock::time_point t4 = boost::chrono::high_resolution_clock::now();
while (t3==t4 ) {
t4 = boost::chrono::high_resolution_clock::now();
}
boost::chrono::nanoseconds ns = t4 - t3;
rdtsc的可能实现
// On some processors in certain circumstances the value can be off
// on some old processors rdtsc doesn't exist.
// only valid for x86/x64.
// only valid when no thread switch happens between calls.
// will be wrong if cpu uses turbo mode or changes speed.
// ToDO check where. make fallback timer.
// will blow up if you run over the epoch, shouldn't happen as the epoch is ~136 years
// beware of cpu instruction reordering if timing very short functions.
static uint64_t tick() noexcept {
unsigned lo, hi;
asm volatile("rdtsc" : "=a" (lo), "=d" (hi));
return int64_t(hi) << 32 | lo;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.