命名空间
变体
操作

std::clock

来自 cppreference.cn
< cpp‎ | chrono‎ | c
 
 
 
 
定义于头文件 <ctime>
std::clock_t clock();

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

只有对 std::clock 的不同调用返回的两个值之间的差值才有意义,因为 std::clock 纪元的开始不必与程序的开始重合。

std::clock 时间可能比挂钟时间走得更快或更慢,具体取决于操作系统为程序提供的执行资源。例如,如果 CPU 由其他进程共享,则 std::clock 时间可能比挂钟时间走得慢。另一方面,如果当前进程是多线程的并且有多个执行核心可用,则 std::clock 时间可能比挂钟时间走得快。

目录

[编辑] 返回值

程序至今使用的处理器时间。

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

[编辑] 异常

不抛出任何异常。

[编辑] 注意

在 POSIX 兼容的系统上,使用时钟 ID CLOCK_PROCESS_CPUTIME_IDclock_gettime 提供更好的分辨率。

clock() 返回的值可能在某些实现上回绕。例如,在这样的实现中,如果 std::clock_t 是一个有符号 32 位整数,并且 CLOCKS_PER_SEC1'000'000,它将在大约 2147 秒(约 36 分钟)后回绕。

[编辑] 示例

此示例演示了 clock() 时间和实际时间之间的差异。

#include <chrono>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <thread>
 
// The function f() does some time-consuming work.
void f()
{
    volatile double d = 0;
    for (int n = 0; n != 10000; ++n)
        for (int m = 0; m != 10000; ++m)
            d += d * n * m;
}
 
int main()
{
    const std::clock_t c_start = std::clock();
    auto t_start = std::chrono::high_resolution_clock::now();
    std::thread t1(f);
    std::thread t2(f); // f() is called on two threads
    t1.join();
    t2.join();
    const std::clock_t c_end = std::clock();
    const auto t_end = std::chrono::high_resolution_clock::now();
 
    std::cout << std::fixed << std::setprecision(2) << "CPU time used: "
              << 1000.0 * (c_end - c_start) / CLOCKS_PER_SEC << "ms\n"
              << "Wall clock time passed: "
              << std::chrono::duration<double, std::milli>(t_end - t_start) << '\n';
}

可能的输出

CPU time used: 1590.00ms
Wall clock time passed: 808.23ms

[编辑] 参见

std::time_t 对象转换为文本表示
(函数) [编辑]
返回系统的当前时间,以自 epoch 以来的时间表示
(函数) [编辑]
C 文档 关于 clock