因為專題需要,筆記一下測試時間的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

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