Namespaces
Variants

clock

From cppreference.net
定义于头文件 <time.h>
clock_t clock ( void ) ;

返回自程序执行相关的实现定义纪元以来,进程使用的近似处理器时间。要将结果值转换为秒,请将其除以 CLOCKS_PER_SEC

只有通过不同调用 clock 返回的两个值之间的差值才具有实际意义,因为 clock 纪元的起始点未必与程序的启动时间重合。

clock 时间可能比挂钟时间流逝得更快或更慢,具体取决于操作系统分配给程序的执行资源。例如,如果 CPU 被其他进程共享, clock 时间可能比挂钟时间流逝得更慢。另一方面,如果当前进程是多线程的且存在多个可用执行核心, clock 时间可能比挂钟时间流逝得更快。

目录

返回值

程序迄今为止使用的处理器时间。

  • 如果处理器使用时间不可用,返回 ( clock_t ) ( - 1 )
  • 如果处理器使用时间的值无法由 clock_t 表示,则返回未指定的值。

注释

在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函数(页码:339)
  • C89/C90 标准 (ISO/IEC 9899:1990):
  • 4.12.2.1 clock 函数

参见

(C23中已弃用) (C11)
time_t 对象转换为文本表示形式
(函数)
返回系统当前日历时间(自纪元起算的时间)
(函数)
C++ 文档 关于 clock