Reputation: 5678
I was trying to program a Timer class (unaware that boost had one), then when that wasn't working, I tried to just output the value of clock(), using this code:
#include <ctime>
#include <iostream>
int main()
{
for(int i = 0; i < 50; ++i)
{
std::cout << std::clock() << " ";
}
return 0;
}
When I run the program, I get a series of 0s. I have a similar experience when using boost thread sleep functions to spread out timing a little longer (although after a few seconds, it jumps from 0 to 10,000 and keeps outputting 10,000).
I'm running Gentoo Linux. Is this a platform thing? A C++ thing? What's going on?
Edit: Strangely the jump to 10000 comes after a number of seconds, not milliseconds. When I was sleeping my thread for a second at a time, it took five or six seconds to get to 10000. However, if I'm understanding correctly. The time the thread spends sleeping doesn't contribute towards the clock() count? (Which would make sense; why would it be executing clock cycles if it's sleeping?)
Upvotes: 3
Views: 10678
Reputation: 93
on my 64 bit operating system the CLOCKS_PER_SEC speed is 1000.and the values of clock comes in milliseconds. perfect timing will be extracted from the code below.
int main(){
clock_t a,b;
int c,d,e,f;
c=clock();
scanf("%d",&e);
d=clock();
f=(d-c)/CLOCKS_PER_SECOND;
printf("timing is %d seconds",f);/*for 64 bit operating system
CLOCKS_PER_SECOND is 1000*/
}
Upvotes: 0
Reputation: 206557
Try the following:
#include <ctime> #include <iostream> int main() { for(int i = 0; i < 50; ++i) { for (int j = 0; j < 500; ++j ) { std::cout << j << " "; } std::cout << std::endl; std::cout << std::clock() << std::endl; } std::cout << std::endl; return 0; }
On my system, I see the return value of clock() staying at 0 until at some point it jumps to 10000. It stays at 10000 till the end. If I remove the std::cout in the inner loop, the return value of clock() stays at 0 all the way through. Looks like clock() returns values in increments of 10000 only.
If I change the inner loop to compute the square root of j and print the return value of sqrt(), the return value of clock() goes up to 50000, but is still increases in increments of 10000.
Upvotes: 0
Reputation: 106530
std::clock
's resolution is unspecified. In most cases, it's resolution is going to be about 10ms
. Hence the jump.
Upvotes: 0
Reputation: 2142
The clock()
return value is specified in microseconds. But typical granularity of whatever low-level system call the clock()
implementation uses is much lower. So it seems that on your system the granularity is 10ms. Also note that clock()
does NOT measure real time - it measures CPU time used by the program. So the time flows when your program controls the CPU, and it freezes when your program is suspended - sleeping, for example.
Upvotes: 7