clock
来自 cppreference.cn
定义于头文件 <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 clock 函数 (p: 285)
- C11 标准 (ISO/IEC 9899:2011)
- 7.27.2.1 clock 函数 (p: 389)
- C99 标准 (ISO/IEC 9899:1999)
- 7.23.2.1 clock 函数 (p: 339)
- C89/C90 标准 (ISO/IEC 9899:1990)
- 4.12.2.1 clock 函数
[编辑] 参见
(在 C23 中弃用)(C11) |
将 time_t 对象转换为文本表示形式 (函数) |
返回系统的当前日历时间,以纪元以来的时间表示 (函数) | |
C++ 文档 for clock
|