通过Clock和stable_clock测量的时间差 [英] Difference in time measured by clock and steady_clock

查看:77
本文介绍了通过Clock和stable_clock测量的时间差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图测量在我的代码中执行特定功能所花费的时间.最初,我使用如下的 clock()函数

I was trying to measure the time taken to execute a specific function in my code. Initially I used the clock() function as below

clock_t start = clock();
do_something();
clock_t end = clock();

printf("Time taken: %f ms\n", ((double) end - start)*1000/CLOCKS_PER_SEC);

稍后,我正在阅读有关 C ++ 11 中的 chrono 库的信息,并尝试使用 std :: chrono :: steady_clock 进行测量.代码>如下

Later I was reading about the chrono library in C++11 and tried to measure the same with a std::chrono::steady_clock as below

using namespace std::chrono;

auto start = steady_clock::now();
do_something();
auto end = steady_clock::now();
printf("Time taken: %lld ms\n", duration_cast<milliseconds>(end - start).count());

第一个代码段(使用 clock )测量的时间为 89.53 ms ,而 steady_clock 所测量的时间为 1140 ms.

The time measured by the first code snippet (using clock) was 89.53 ms and that measured by steady_clock was 1140 ms.

为什么两个时钟所测量的时间差异如此之大?

Why is there such a big difference in time measured by both the clocks?

推荐答案

clock 测量处理器时间,而 steady_clock 测量物理时间.因此,如果 do_something()被其他进程(例如检查邮件或其他东西)抢占了,则您会得到这样的区别.

clock measures processor time, whereas steady_clock measures physical time. So you can get differences like this if do_something() was preempted by other processes (such as checking mail or whatever).

Daniel H 在下面的评论中指出了一个要点,即如果 do_something()不受CPU限制.例如,如果它睡眠,阻塞锁定互斥锁,等待条件变量等.

Daniel H makes a great point below in the comments that this can also happen if do_something() isn't CPU bound. For example if it sleeps, blocks on locking a mutex, waits on a condition variable, etc.

这篇关于通过Clock和stable_clock测量的时间差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆