命名空间
变体
操作

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 对象转换为文本表示
(函数) [编辑]
返回系统当前时间,作为自纪元以来的时间
(函数) [编辑]
C 文档 用于 clock