它是 C++11 中非常易于使用的方法.您必须使用 标头中的 std::chrono::high_resolution_clock.
像这样使用它:
#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
";
std::cout << ms_double.count() << "ms";
return 0;
}
这将测量函数long_operation的持续时间.
可能的输出:
150ms
150.068ms
工作示例:https://godbolt.org/z/oe5cMd
这篇关于在 C++ 中测量函数的执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持前端之家!
本文链接:https://www.f2er.com/3188526.html