首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::clock

Defined in header <ctime>

std::clock_t clock();

返回自与程序%27s执行相关的实现定义时代开始以来进程使用的近似处理器时间。将结果值转换为秒除以CLOCKS_PER_SEC...

的不同调用返回的两个值之间的差异。std::clock是有意义的,作为std::clock时代并不一定要与项目的开始相吻合。std::clock根据操作系统给程序的执行资源,时间可能比挂钟前进得更快或更慢。例如,如果CPU由其他进程共享,std::clock时间的进展可能比挂钟慢。另一方面,如果当前进程是多线程的,并且有多个执行核心可用,std::clock时间可能比挂钟快。

参数

%280%29

返回值

程序迄今使用的处理器时间或(clock_t)(-1)如果该信息不可用或其值无法表示。

例外

%280%29

注记

关于POSIX兼容系统,clock_gettime带时钟idCLOCK_PROCESS_CPUTIME_ID提供更好的分辨率。

返回的值clock()可能会对某些实现进行包装。例如,在32位的机器上。std::clock_t,它在2147后包装,时间是36秒或36分钟。

此示例演示了时钟%28%29时间与实时时钟之间的区别。

二次

代码语言:javascript
复制
#include <iostream>
#include <iomanip>
#include <chrono>
#include <ctime>
#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()
{
    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();
    std::clock_t c_end = std::clock();
    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).count()
              << " ms\n";
}

二次

产出:

二次

代码语言:javascript
复制
CPU time used: 1590.00 ms
Wall clock time passed: 808.23 ms

二次

另见

ctime

converts a time_t object to a textual representation (function)

time

returns the current time of the system as time since epoch (function)

c时钟文件

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券