如何計算 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 千瀏覽量

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告