C++ calculating time intervals

后端 未结 5 1357
情歌与酒
情歌与酒 2021-01-22 08:05

I want to calculate time intervals (in 1/10th of 1 second) between some events happening in my program. Thus I use clock function for these needs like follows:

相关标签:
5条回答
  • 2021-01-22 08:11

    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.

    0 讨论(0)
  • 2021-01-22 08:19

    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.

    0 讨论(0)
  • 2021-01-22 08:20

    Maybe you have to typecast it to double.

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

    Integers get rounded, probably to 0 in your case.

    0 讨论(0)
  • 2021-01-22 08:21

    Read about the time() function.

    0 讨论(0)
  • 2021-01-22 08:33

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

    0 讨论(0)
提交回复
热议问题