如何计算 C++ 中代码片段的执行时间?


我们可以使用以下语法来计算代码片段的执行时间 -

auto start = high_resolution_clock::now(); // Start time
// Code snippet
auto stop = high_resolution_clock::now(); // Stop time
auto duration = duration_cast<microseconds>(stop - start); // Duration

类 high_resolution_clock 在“chrono”头文件中定义。函数 now() 返回与调用时间点相对应的一个值。

一个头文件用于记录特定代码所花费的时间。

#include <chrono>
using namespace std::chrono;

以下是一个计算代码片段的执行时间的示例。

示例

 在线演示

#include <iostream>
#include <chrono>
using namespace std::chrono;
using namespace std;
int sum(int x, int y) {
   int s = x + y;
   cout << "The sum of numbers : " << s;
}
int main() {
   auto start = high_resolution_clock::now();
   sum(28, 8);
   auto stop = high_resolution_clock::now();
   auto duration = duration_cast<microseconds>(stop - start);
   cout << "\nTime taken by function : "<< duration.count() << " microseconds";
   return 0;
}

输出

The sum of numbers : 36
Time taken by function : 42 microseconds

在上面的程序中,定义了一个函数 sum() 来计算数字之和。

int sum(int x, int y) {
   int s = x + y;
   cout << "The sum of numbers : " << s;
}

在 main() 函数中,我们使用一些预定义的函数和类“chrono”来记录函数 sum() 所花费的时间。

auto start = high_resolution_clock::now();
sum(28, 8);
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);

更新于: 26-6-2020

2 千浏览量

开启你的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.