我想用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:35:49
如果您想测量非常快的代码片段的持续时间,通常一个好主意是多次运行它们并计算所有运行的平均时间,那么您提到的~200 is将可以忽略不计,因为它们分布在所有运行中。
示例:
#include <cstdio>
#include <chrono>
using clock = std::chrono::high_resolution_clock;
auto start = clock::now();
int n = 10000; // adjust depending on the expected runtime of your code
for (unsigned int i = 0; i < n; ++i)
functionYouWantToTime();
auto result =
std::chrono::duration_cast<std::chrono::nanoseconds>(start - clock::now()).count() / n;发布于 2019-03-16 03:35:49
只是不要将时间时钟用于纳秒基准测试。取而代之的是使用CPU节拍-在任何现代的硬件上,CPU节拍都是单调的、稳定的,并且在内核之间是同步的。
不幸的是,C++不公开CPU tick时钟,所以你必须直接使用RDTSC指令(它可以很好地包装在内联函数中,也可以使用编译器的内部函数)。如果您愿意,也可以将CPU节拍的差异转换为时间(通过使用CPU频率),但通常对于这样的低延迟基准测试,这并不是必需的。
发布于 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
复制相似问题