problem with clock()

Really simple program...

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
#include <time.h>

int main()
{
	double elapsed=0;
	while(elapsed <= 10){
		elapsed = clock()/(double)CLOCKS_PER_SEC;
		printf("elapsed time: %lf\n", elapsed);
	}
}


I was expecting this to print the number of seconds since the program started running, over and over again for 10 seconds. Instead, it takes much longer than 10 seconds, and sometimes I can see the numbers speeding up or slowing down during execution.

Why is this? Does it only count the clock cycles that this application is using? Is there a better way to keep track of elapsed time regardless of CPU usage?

Also, the resolution is only hundredths of seconds. After the second decimal place it prints all zeroes. How can I get milliseconds or even finer resolution?
Its possible that writing to the output device (the console) is taking longer than the execution of the program itself.

Try running the program with no output and timing it. It may well run much faster.

When I ran it sending the output to /dev/null it took 11 seconds


real	0m11.083s


But running it printing to the console took much longer, nearly a whole minute:


real	0m59.908s




Last edited on
Here is a version that only writes to the console once per second, rather than thousands of times a second:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <ctime>
#include <iostream>

int main()
{
	double elapsed=0;
	double last = 0;
	while(elapsed <= 10){
		elapsed = clock()/(double)CLOCKS_PER_SEC;
		if(elapsed - last > 1)
		{
			std::cout << "elapsed time: " << elapsed << std::endl;
			last = elapsed;
		}
	}

	return 0;
}


I think this will do what you expect.
Topic archived. No new replies allowed.