clock
來自 cppreference.com
定義於標頭檔案 <time.h> |
||
clock_t clock(void); |
||
返回自與程式執行相關的、實現定義時期開始以來,程序所使用的近似處理器時間。要將結果值轉換為秒,請將其除以 CLOCKS_PER_SEC。
只有兩次不同調用 clock
所返回的值之間的差值才有意義,因為 clock
時期的開始不一定與程式開始時間重合。
clock
時間的推進速度可能快於或慢於現即時間,這取決於作業系統分配給程式的執行資源。例如,如果 CPU 被其他程序共享,clock
時間可能比現即時間慢。另一方面,如果當前程序是多執行緒的並且有多個執行核心可用,clock
時間可能比現即時間快。
目錄 |
[編輯] 返回值
程式迄今為止使用的處理器時間。
[編輯] 注意
在相容 POSIX 的系統上,使用時鐘 ID CLOCK_PROCESS_CPUTIME_ID 的 clock_gettime
提供更好的解析度。
clock()
返回的值在某些實現上可能會溢位。例如,在此類實現上,如果 clock_t 是有符號 32 位整數且 CLOCKS_PER_SEC 是 1000000,它將在大約 2147 秒(約 36 分鐘)後溢位。
[編輯] 示例
此示例演示了 clock()
時間與即時之間的差異。
執行此程式碼
#ifndef __STDC_NO_THREADS__ #include <threads.h> #else // POSIX alternative #define _POSIX_C_SOURCE 199309L #include <pthread.h> #endif #include <stdio.h> #include <stdlib.h> #include <time.h> // the function f() does some time-consuming work int f(void* thr_data) // return void* in POSIX { (void) thr_data; volatile double d = 0; for (int n = 0; n < 10000; ++n) for (int m = 0; m < 10000; ++m) d += d * n * m; return 0; } int main(void) { struct timespec ts1, tw1; // both C11 and POSIX clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts1); // POSIX clock_gettime(CLOCK_MONOTONIC, &tw1); // POSIX; use timespec_get in C11 clock_t t1 = clock(); #ifndef __STDC_NO_THREADS__ thrd_t thr1, thr2; // C11; use pthread_t in POSIX thrd_create(&thr1, f, NULL); // C11; use pthread_create in POSIX thrd_create(&thr2, f, NULL); thrd_join(thr1, NULL); // C11; use pthread_join in POSIX thrd_join(thr2, NULL); #endif struct timespec ts2, tw2; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts2); clock_gettime(CLOCK_MONOTONIC, &tw2); clock_t t2 = clock(); double dur = 1000.0 * (t2 - t1) / CLOCKS_PER_SEC; double posix_dur = 1000.0 * ts2.tv_sec + 1e-6 * ts2.tv_nsec - (1000.0 * ts1.tv_sec + 1e-6 * ts1.tv_nsec); double posix_wall = 1000.0 * tw2.tv_sec + 1e-6 * tw2.tv_nsec - (1000.0 * tw1.tv_sec + 1e-6 * tw1.tv_nsec); printf("CPU time used (per clock()): %.2f ms\n", dur); printf("CPU time used (per clock_gettime()): %.2f ms\n", posix_dur); printf("Wall time passed: %.2f ms\n", posix_wall); }
可能的輸出
CPU time used (per clock()): 1580.00 ms CPU time used (per clock_gettime()): 1582.76 ms Wall time passed: 792.13 ms
[編輯] 參考
- C17 標準 (ISO/IEC 9899:2018)
- 7.27.2.1 The clock function (p: 285)
- C11 標準 (ISO/IEC 9899:2011)
- 7.27.2.1 The clock function (p: 389)
- C99 標準 (ISO/IEC 9899:1999)
- 7.23.2.1 The clock function (p: 339)
- C89/C90 標準 (ISO/IEC 9899:1990)
- 4.12.2.1 The clock function
[編輯] 另請參閱
(C23 中已廢棄)(C11) |
將 time_t 物件轉換為文字表示形式 (函式) |
返回系統當前日曆時間,自紀元起的時間 (函式) | |
C++ 文件 for clock
|