©
本文档使用
php中文网手册 发布
在头文件<time.h>中定义 | ||
|---|---|---|
clock_t clock(void); |
返回与程序执行相关的实现定义时代开始以来进程使用的近似处理器时间。要将结果值转换为秒,请将其除以CLOCKS_PER_SEC。
只有不同调用返回的两个值之间的差异clock才有意义,因为clock时代的开始并不一定与程序的开始一致。clock时间可能比挂钟提前或延迟,这取决于操作系统给予程序的执行资源。例如,如果CPU由其他进程共享,则clock时间可能比挂钟慢。另一方面,如果当前进程是多线程的并且有多个执行核心可用,则clock时间可能比壁钟提前得更快。
(none).
到目前为止程序使用的处理器时间,或者(clock_t)(-1)如果该信息不可用或其值不能表示。
在POSIX兼容系统上,clock_gettime使用时钟ID CLOCK_PROCESS_CPUTIME_ID可以提供更好的分辨率。
返回的值clock()可能会在一些实现中环绕。例如,在一台32位的机器上clock_t,它会在2147秒或36分钟后打包。
这个例子演示了clock()时间和实时之间的区别。
#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标准(ISO / IEC 9899:2011):
7.27.2.1时钟功能(p:389)
C99标准(ISO / IEC 9899:1999):
7.23.2.1时钟功能(p:339)
C89 / C90标准(ISO / IEC 9899:1990):
4.12.2.1时钟功能