C ++ Clock()函数给出不正确的值 [英] C++ clock() function giving incorrect values

查看:401
本文介绍了C ++ Clock()函数给出不正确的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个Timer类(不知道boost有一个),然后当它不起作用时,我尝试使用以下代码输出Clock()的值:

  #include< ctime> 
#include< iostream>

int main()
{
for(int i = 0; i <50; ++ i)
{
std :: cout << std :: clock()<< ;
}
返回0;
}

运行程序时,得到一系列的0。使用升压线程睡眠功能将时间分配得更长一些时,我也有类似的经历(尽管几秒钟后,它从0跳到10,000,并保持输出10,000)。



<我正在运行Gentoo Linux。这是平台的东西吗? C ++的东西?发生了什么事?



编辑:奇怪的是,在经过(而不是毫秒)后才跳到10000。当我一次使线程休眠一秒钟时,花了五到六秒钟才达到10000。但是,如果我理解正确的话。线程花费在睡眠上的时间不会增加clock()的计数吗? (这有道理;如果它处于睡眠状态,为什么还要执行时钟周期?)

解决方案

clock()返回值以微秒为单位。但是,任何低级系统调用 clock()实现所使用的典型粒度要低得多。因此,看来您的系统上的粒度为10ms。另请注意, clock()不能测量实时时间-它测量程序使用的CPU时间。因此,时间流逝在您的程序控制CPU时,并且在程序暂停时冻结(例如,休眠)。


I was trying to program a Timer class (unaware that boost had one), then when that wasn't working, I tried to just output the value of clock(), using this code:

#include <ctime>
#include <iostream>

int main()
{
 for(int i = 0; i < 50; ++i)
 {
  std::cout << std::clock() << " ";
 }
 return 0;
}

When I run the program, I get a series of 0s. I have a similar experience when using boost thread sleep functions to spread out timing a little longer (although after a few seconds, it jumps from 0 to 10,000 and keeps outputting 10,000).

I'm running Gentoo Linux. Is this a platform thing? A C++ thing? What's going on?

Edit: Strangely the jump to 10000 comes after a number of seconds, not milliseconds. When I was sleeping my thread for a second at a time, it took five or six seconds to get to 10000. However, if I'm understanding correctly. The time the thread spends sleeping doesn't contribute towards the clock() count? (Which would make sense; why would it be executing clock cycles if it's sleeping?)

解决方案

The clock() return value is specified in microseconds. But typical granularity of whatever low-level system call the clock() implementation uses is much lower. So it seems that on your system the granularity is 10ms. Also note that clock() does NOT measure real time - it measures CPU time used by the program. So the time flows when your program controls the CPU, and it freezes when your program is suspended - sleeping, for example.

这篇关于C ++ Clock()函数给出不正确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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