- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - clock() 函式
C 庫的 clock() 函式返回程式啟動以來經過的時鐘滴答數。要獲取 CPU 使用的秒數,我們需要除以 CLOCKS_PER_SEC。在 CLOCKS_PER_SEC 等於 1000000 的 32 位系統上,此函式大約每 72 分鐘返回相同的值。
CLOCKS_PER_SEC 是一種用於構建時間程式的宏。
語法
以下是 C 庫 clock() 函式的語法:
clock_t clock(void)
引數
- 此函式不接受任何引數。
返回值
此函式返回程式啟動以來經過的時鐘滴答數。如果失敗,則返回 -1。
示例 1
以下是一個基本的 C 庫程式,用於演示 clock() 函式。
#include <time.h>
#include <stdio.h>
int main () {
clock_t start_t, end_t;
double total_t;
int i;
start_t = clock();
printf("Starting of the program, start_t = %ld\n", start_t);
printf("Going to scan a big loop, start_t = %ld\n", start_t);
for(i=0; i< 10000000; i++) {
}
end_t = clock();
printf("End of the big loop, end_t = %ld\n", end_t);
total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
printf("Total time taken by CPU: %f\n", total_t );
printf("Exiting of the program...\n");
return(0);
}
以上程式碼產生以下結果:
Starting of the program, start_t = 1194 Going to scan a big loop, start_t = 1194 End of the big loop, end_t = 26796 Total time taken by CPU: 0.025602 Exiting of the program...
示例 2
在本例中,我們使用 clock() 函式演示了各種操作的處理器時間(以秒為單位)的測量。
#include <stdio.h>
#include <time.h>
#include <math.h>
int main() {
float a;
clock_t time_req;
// Measure time for multiplication
time_req = clock();
for (int i = 0; i < 200000; i++) {
a = log(i * i * i * i);
}
time_req = clock() - time_req;
printf("Processor time taken for multiplication: %f seconds\n", (float)time_req / CLOCKS_PER_SEC);
// Measure time using pow function
time_req = clock();
for (int i = 0; i < 200000; i++) {
a = log(pow(i, 4));
}
time_req = clock() - time_req;
printf("Processor time taken in pow function: %f seconds\n", (float)time_req / CLOCKS_PER_SEC);
return 0;
}
輸出
執行以上程式碼後,我們得到以下結果:
Processor time taken for multiplication: 0.005235 seconds Processor time taken in pow function: 0.010727 seconds
廣告