```c++
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h> // clock 函數所需之標頭檔
double pi(int n) {
srand(5);
int count = 0;
double x, y;
for (int i = 0; i < n; ++i) {
x = (double) rand() / RAND_MAX;
y = (double) rand() / RAND_MAX;
if (x * x + y * y <= 1) ++count;
}
return (double) count / n * 4;
}
int main() {
// 儲存時間用的變數
clock_t start, end;
double cpu_time_used;
// 計算開始時間
start = clock();
// 主要計算
double result = pi(1e8);
// 計算結束時間
end = clock();
// 計算實際花費時間
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("PI = %f\n", result);
printf("Time = %f\n", cpu_time_used);
}
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.
windows.h
中的QueryPerformanceCount / QueryPerformanceFrequency, 精度達微秒,但在 MSDN 上亦註明,此函式若硬體不支援,將只傳回 1000clock
clock()
會回傳「程式開始執行」到「clock本行程式碼被執行」時的時間差,回傳型別為clock_t
clock()
會在程式開始執行時計時,直接呼叫就能知道已經執行多久由於 clock 回傳的數值是以毫秒為單位,所以會在除上一個 CLOCKS_PER_SEC,這個 CLOCKS_PER_SEC 通常都是 1000
可以差值測試某一段程式所需的時間
clock_gettime
clock_gettime 的 prototype 如下
選擇要拿哪個 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
用一個簡單的for loop來計算執行時間
QueryPerformanceCount / QueryPerformanceFrequency
: 這應是目前精度最高之函式,精度達微秒,但在 MSDN 上亦註明,此函式若硬體不支援,將只傳回 1000,再用 GetTickCount 代替它 (如果我沒意會錯的話應為如此)。使用此函式時將較耗資源。參考資料 https://jerrynest.io/calculate-running-time/ https://blog.gtwang.org/programming/measure-the-execution-time-in-c-language/ https://www.guyrutenberg.com/2007/09/22/profiling-code-using-clock_gettime/