简体   繁体   English

C ++中的时间不正确

[英]Incorrect Time in C++

I have the following code: 我有以下代码:

clock_t tt = clock();
sleep(10);
tt = clock()-tt;
cout<<(float)tt/CLOCKS_PER_SEC<<" "<<CLOCKS_PER_SEC<<endl;

When I run the code, it apparently pauses for 10 seconds and the output is: 当我运行代码时,它显然会暂停10秒钟,输出为:

0.001074 1000000 0.001074 1000000

This indicates it passed 1074 clock ticks and 1ms, which is apparently false. 这表明它通过了1074个时钟滴答和1ms,这显然是错误的。

Why does this happen? 为什么会这样?

I am using g++ under linux. 我在Linux下使用g ++。

The function clocks returns the processor time consumed by the program. 该函数时钟返回程序消耗的处理器时间。 While sleeping, your process does not use any amount of processing, so this is expected. 在休眠期间,您的进程不会使用任何数量的处理,因此这是可以预期的。 The amount of time your program is showing could be from the clock function calling. 程序显示的时间可能来自clock函数调用。

clock() doesn't measure elapsed time (what you would measure with a stopwatch), it measures the time spent by your program running on the CPU. clock()不测量经过的时间(用秒表测量的时间),它测量在CPU上运行程序所花费的时间。 But sleep() almost don't use any CPU, it simply makes your process going to sleep. 但是sleep()几乎不使用任何CPU,它只是使您的进程进入睡眠状态。 Try to modify sleep(10) by any other value sleep(1) for example, and you will get the same result. 尝试用任何其他值sleep(1)修改sleep(10) ,您将得到相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM