我想用std::chrono时钟测量一段代码的持续时间,但它似乎太重了,无法测量持续纳秒的东西。该程序:
#include <cstdio>
#include <chrono>
int main() {
using clock = std::chrono::high_resolution_clock;
// try several times
for (int i = 0; i < 5; i++) {
// two consequent now() here, one right after another without anything in between
printf("%dns\n", (int)std::chrono::duration_cast<std::chrono::nanoseconds>(clock::now() - clock::now()).count());
}
return 0;
}总能给我100-300纳秒。这是因为两个syscall吗?现在两次之间的持续时间有可能更短吗()?谢谢!
运行环境: Linux Ubuntu 18.04,内核4.18,平均负载低,stdlib动态链接。
发布于 2019-03-16 03:38:17
使用rdtsc指令以最高的分辨率和尽可能最低的开销测量时间:
#include <iostream>
#include <cstdint>
int main() {
uint64_t a = __builtin_ia32_rdtsc();
uint64_t b = __builtin_ia32_rdtsc();
std::cout << b - a << " cpu cycles\n";
}输出:
19 cpu cycles要将周期转换为纳秒,请将周期除以GHz中的基本CPU频率。例如,对于4.2 4.2 i7-7700k除以4.2。
TSC是CPU中跨所有内核共享的全局计数器。
现代CPU有一个恒定的TSC,无论当前CPU频率和升压如何,TSC都会以相同的速率运行。在/proc/cpuinfo,flags字段中查找constant_tsc。
另请注意,__builtin_ia32_rdtsc比内联程序集更有效,请参见https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48877
https://stackoverflow.com/questions/55189419
复制相似问题