我想知道在我的c++程序中某个函数在Linux上执行需要多少时间。之后,我想做一个速度比较。我看到了几个时间函数,但最终从boost。空间:
process_user_cpu_clock, captures user-CPU time spent by the current process
现在,我不清楚如果我使用上述函数,我会得到哪个CPU在该函数上花费的唯一时间吗?
其次,我找不到任何使用上述功能的例子。请问有谁能告诉我如何使用上面的功能?
p.s.:现在,我使用std::chrono::system_clock::now()以秒为单位获得时间,但这给了我不同的结果,因为不同的CPU负载每次。
因为没有一个提供的答案是非常准确的或可复制的结果,我决定添加一个链接到我的代码,具有亚纳秒的精度和科学统计。
Note that this will only work to measure code that takes a (very) short time to run (aka, a few clock cycles to a few thousand): if they run so long that they are likely to be interrupted by some -heh- interrupt, then it is clearly not possible to give a reproducable and accurate result; the consequence of which is that the measurement never finishes: namely, it continues to measure until it is statistically 99.9% sure it has the right answer which never happens on a machine that has other processes running when the code takes too long.
https://github.com/CarloWood/cwds/blob/master/benchmark.h#L40
#include <iostream>
#include <chrono>
void function()
{
// code here;
}
int main()
{
auto t1 = std::chrono::high_resolution_clock::now();
function();
auto t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
std::cout << duration<<"/n";
return 0;
}
这对我很管用。
注意:
high_resolution_clock不能在不同的标准库实现中实现一致,应该避免使用它。它通常只是std::chrono::steady_clock或std::chrono::system_clock的别名,但它是哪一个取决于库或配置。当它是system_clock时,它不是单调的(例如,时间可以倒退)。
例如,对于gcc的libstdc++,它是system_clock,对于MSVC,它是steady_clock,对于clang的libc++,它取决于配置。
通常应该直接使用std::chrono::steady_clock或std::chrono::system_clock,而不是std::chrono::high_resolution_clock:使用steady_clock测量持续时间,使用system_clock测量时钟时间。