C++ calculating time intervals

删除回忆录丶 提交于 2019-12-02 02:03:53

The clock() function returns the amount of CPU time charged to your program. When you are blocked inside a usleep() call, no time is being charged to you, making it very clear why your time never seems to increase. As to why you seem to be taking 8 seconds to be charged one second -- there are other things going on within your system, consuming CPU time that you would like to be consuming but you must share the processor. clock() cannot be used to measure the passage of real time.

I bet your printing so much to stdout that old prints are getting buffered. The buffer is growing and the output to the console can't keep up with your tight loop. By adding the sleep you're allowing the buffer some time to flush and catch up. So even though its 8 seconds into your program, your printing stuff from 8 seconds ago.

I'd suggest putting the actual timestamp into the print statement. See if the timestamp is lagging significantly from the actual time.

If you're able to use boost, checkout the Boost Timers library.

Maybe you have to typecast it to double.

cout << (double)(diff / CLOCKS_PER_SEC) << "\n";

Integers get rounded, probably to 0 in your case.

Read about the time() function.

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