问题
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:
clock_t begin;
clock_t now;
clock_t diff;
begin = clock();
while ( 1 )
{
now = clock();
diff = now - begin;
cout << diff / CLOCKS_PER_SEC << "\n";
//usleep ( 1000000 );
};
I expect the program to print 0
for 1 second, then 1
for 1 sec., then 2
for 1 sec. and so on... In fact it prints 0
for about 8 seconds, then 1
for about 8 seconds and so on...
By the way, if I add usleep
in order program prints only 1 time per second, it prints only 0
all way long...
Great thanks for help!
回答1:
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.
回答2:
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.
回答3:
If you're able to use boost, checkout the Boost Timers library.
回答4:
Maybe you have to typecast it to double.
cout << (double)(diff / CLOCKS_PER_SEC) << "\n";
Integers get rounded, probably to 0 in your case.
回答5:
Read about the time()
function.
来源:https://stackoverflow.com/questions/12020948/c-calculating-time-intervals