Incorrect Time in C++

為{幸葍}努か 提交于 2020-06-17 03:44:07

问题


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:

0.001074 1000000

This indicates it passed 1074 clock ticks and 1ms, which is apparently false.

Why does this happen?

I am using g++ under linux.


回答1:


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.




回答2:


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. But sleep() almost don't use any CPU, it simply makes your process going to sleep. Try to modify sleep(10) by any other value sleep(1)for example, and you will get the same result.



来源:https://stackoverflow.com/questions/24292507/incorrect-time-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!