?
このドキュメントでは、 php中國語ネットマニュアル リリース
在頭文件<time.h>中定義 | ||
---|---|---|
clock_t clock(void); |
返回與程序執(zhí)行相關(guān)的實(shí)現(xiàn)定義時(shí)代開始以來進(jìn)程使用的近似處理器時(shí)間。要將結(jié)果值轉(zhuǎn)換為秒,請(qǐng)將其除以CLOCKS_PER_SEC
。
只有不同調(diào)用返回的兩個(gè)值之間的差異clock
才有意義,因?yàn)?code>clock時(shí)代的開始并不一定與程序的開始一致。clock
時(shí)間可能比掛鐘提前或延遲,這取決于操作系統(tǒng)給予程序的執(zhí)行資源。例如,如果CPU由其他進(jìn)程共享,則clock
時(shí)間可能比掛鐘慢。另一方面,如果當(dāng)前進(jìn)程是多線程的并且有多個(gè)執(zhí)行核心可用,則clock
時(shí)間可能比壁鐘提前得更快。
(none).
到目前為止程序使用的處理器時(shí)間,或者(clock_t)(-1)
如果該信息不可用或其值不能表示。
在POSIX兼容系統(tǒng)上,clock_gettime
使用時(shí)鐘ID CLOCK_PROCESS_CPUTIME_ID
可以提供更好的分辨率。
返回的值clock()
可能會(huì)在一些實(shí)現(xiàn)中環(huán)繞。例如,在一臺(tái)32位的機(jī)器上clock_t
,它會(huì)在2147秒或36分鐘后打包。
這個(gè)例子演示了clock()時(shí)間和實(shí)時(shí)之間的區(qū)別。
#include <stdio.h>#include <time.h>#include <stdlib.h>#include <threads.h> // pthread.h in POSIX // the function f() does some time-consuming workint f(void* thr_data) // return void* in POSIX{ 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(); 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); 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
C11標(biāo)準(zhǔn)(ISO / IEC 9899:2011):
7.27.2.1時(shí)鐘功能(p:389)
C99標(biāo)準(zhǔn)(ISO / IEC 9899:1999):
7.23.2.1時(shí)鐘功能(p:339)
C89 / C90標(biāo)準(zhǔn)(ISO / IEC 9899:1990):
4.12.2.1時(shí)鐘功能