[C/C++] 計算程式執行時間

因為專題需要,筆記一下測試時間的 function

  1. 使用 clock() 精確度只到 ms
  2. 使用 clock_gettime(),精確度可達 ns

clock

clock 會在程式開始執行時計時,直接呼叫就能知道已經執行多久

cout << (double)clock() / CLOCKS_PER_SEC << " S";

由於 clock 回傳的數值是以毫秒為單位,所以會在除上一個 CLOCKS_PER_SEC,這個 CLOCKS_PER_SEC 通常都是 1000


clock_gettime

clock_gettime 的 prototype 如下

int clock_gettime(clockid_t clk_id, struct timespect *tp);

選擇要拿哪個 clock 的時間,放入 clk_id 這欄位,以下是較常用的 clock

  • CLOCK_REALTIME, a system-wide realtime clock.
  • CLOCK_PROCESS_CPUTIME_ID, high-resolution timer provided by the CPU for each process.
  • CLOCK_THREAD_CPUTIME_ID, high-resolution timer provided by the CPU for each of the threads.

timespect 這個 struct 有兩個 member,tv_sec 與 tv_nsec

請支持《傑瑞窩在這》原創文章。原文標題:[C/C++] 計算程式執行時間,原文網址:https://jerrynest.io/calculate-running-time/
struct timespec {
      time_t tv_sec; /* seconds */
    long tv_nsec; /* nanoseconds */
};

簡單測試程式

用一個簡單的遞迴題目來計算執行時間

A robot can take steps of 1 meter, 2 meters and 3 meters. Write a recursive function num_of_ways to evaluate the number of ways the robot can walk n meters.
#include <iostream>
#include <time.h>
using namespace std;

int num_of_ways(int);

double timeStart, timeEnd;
timespec time1, time2;

timespec diff(timespec start, timespec end) {
  timespec temp;
  if ((end.tv_nsec - start.tv_nsec) < 0) {
    temp.tv_sec = end.tv_sec - start.tv_sec - 1;
    temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
  } else {
    temp.tv_sec = end.tv_sec - start.tv_sec;
    temp.tv_nsec = end.tv_nsec - start.tv_nsec;
  }
  return temp;
}

int main() {

  int n, r;
  cout << "Please enter n: ";
  cin >> n;
  timeStart = clock();
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, & time1);
  r = num_of_ways(n);
  timeEnd = clock();
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, & time2);
  cout << "number of ways = " << r << endl;
  cout << "total time (clock) = " << (timeEnd– timeStart) / CLOCKS_PER_SEC << " s" << endl;
  cout << "total time (clock_gettime) = " << diff(time1, time2).tv_sec << ":" << diff(time1, time2).tv_nsec << endl;
  return 0;

}

int num_of_ways(int n) {

  if (n == 3)
    return 4;
  else if (n == 2)
    return 2;
  else if (n == 1)
    return 1;
  else
    return (num_of_ways(n - 1) + num_of_ways(n - 2) + num_of_ways(n - 3));
}

輸入 n = 25,得到以下結果,精確度真的差很多

Please enter n: 35
number of ways = 1132436852
total time (clock) = 1.52331 s
total time (clock_gettime) = 1.523312594 s


參考資料

[C/C++] 計算程式效率 & 執行時間 Profiling Code Using clock_gettime

如果您覺得這篇文章有幫助,歡迎按個讚或分享出去唷:

樂於分享的軟體工程師,曾在新創與大型科技公司實習,獲得黑客松競賽冠軍,擔任資安研討會講者。長期熱衷於資訊安全、雲端服務、網路行銷等領域,希望將科技知識分享給更多人。內容轉載請來信:jlee58tw@gmail.com

發表回應