我想知道我的 C++ 程序中某个函数执行需要多长时间Linux。之后我想做一个速度对比。我看到了几个 time 函数,但最终从 boost 中得到了这个。时间:
process_user_cpu_clock, captures user-CPU time spent by the current process
现在,我不清楚如果我使用上述函数,我是否会得到该函数上花费的唯一CPU时间?
其次,我找不到任何使用上述功能的示例。谁能帮我看看如何使用上述功能吗?
P.S:现在,我正在使用std::chrono::system_clock::now()
获得以秒为单位的时间,但是由于每次 CPU 负载不同,这给了我不同的结果。
这是C++11中非常好用的方法。你必须使用std::chrono::high_resolution_clock
from <chrono>
header.
像这样使用它:
#include <chrono>
/* Only needed for the sake of this example. */
#include <iostream>
#include <thread>
void long_operation()
{
/* Simulating a long, heavy operation. */
using namespace std::chrono_literals;
std::this_thread::sleep_for(150ms);
}
int main()
{
using std::chrono::high_resolution_clock;
using std::chrono::duration_cast;
using std::chrono::duration;
using std::chrono::milliseconds;
auto t1 = high_resolution_clock::now();
long_operation();
auto t2 = high_resolution_clock::now();
/* Getting number of milliseconds as an integer. */
auto ms_int = duration_cast<milliseconds>(t2 - t1);
/* Getting number of milliseconds as a double. */
duration<double, std::milli> ms_double = t2 - t1;
std::cout << ms_int.count() << "ms\n";
std::cout << ms_double.count() << "ms\n";
return 0;
}
这将测量函数的持续时间long_operation
.
可能的输出:
150ms
150.068ms
工作示例:https://godbolt.org/z/oe5cMd https://godbolt.org/z/oe5cMd
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)