std:: clock
|
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
定义于头文件
<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_ID
的
clock_gettime
可提供更精确的时间分辨率。
在某些实现中,
clock()
返回的值可能会发生回绕。例如,在此类实现中,若
std::clock_t
为有符号32位整数且
CLOCKS_PER_SEC
为
1
'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
的内容
|
|