I'm not getting the elapsed time in seconds

Viewed 664

I need to know the elapsed time of my program in seconds. Just the elapsed time, I'm not doing anything in between, so I DON'T need the time between two events, all I want to do is already in the code.

clock_t begin = clock();
float timeElapsed = (float)begin/(CLOCKS_PER_SEC);
cout << timeElapsed << endl;

The problem is, the "time" is being printed, but it is not in seconds. I even compared it with a chronometer, and it definitely is not in seconds. When something like "1.27818" appears on the screen, I expect it to be 1.27818 seconds, but it is clearly not. It takes too much time to get to 1 and this time is definitely not one second. What's going on? Wasn't "(float)begin/(CLOCKS_PER_SEC)" supposed to return in seconds?

UPDATE
I did this:

clock_t begin = clock();
float timeElapsed = (float)(clock() - begin)/(CLOCKS_PER_SEC);
cout << timeElapsed << endl;

But I'm getting values like these:

0
1e-06
1e-06
0
1e-06
1e-06
2e-06
1e-06
3 Answers

Take a look at this example:

int main ()
{
  clock_t t;
  int f;
  t = clock();
  printf ("Calculating...\n");
  f = call_some_function();
  printf ("Result: %d\n",f);
  t = clock() - t;
  printf ("It took me %d clicks (%f seconds).\n",t,((float)t)/CLOCKS_PER_SEC);
  return 0;
}

One thing to note is you might want to do subtraction of clock() - begin after the operation, to get the time elapsed of the operation.

The values you got are in scientific notation, if you want plain form you should use std::fixed stream manipulator. For example:

std::cout << std::fixed << data;

Also documents about std::clock() say:

Only the difference between two values returned by different calls to std::clock is meaningful, as the beginning of the std::clock era does not have to coincide with the start of the program. std::clock time may advance faster or slower than the wall clock, depending on the execution resources given to the program by the operating system. For example, if the CPU is shared by other processes, std::clock time may advance slower than wall clock. On the other hand, if the current process is multithreaded and more than one execution core is available, std::clock time may advance faster than wall clock.

Also there's a good example at the bottom of that page.

You need a starting time and an ending time. Subtract them and then divide it by CLOCKS_PER_SEC.

Do this:

clock_t begin = clock();
/* 

Do your process

*/
clock_t end = clock();
float timeElapsed = (float)(end-begin)/(CLOCKS_PER_SEC);
cout << timeElapsed << endl;

You get the answer in ticks, in scientific notations. Note that 1 second= 10^6 ticks. You need to multiply your answer by 1 million to get answer in seconds.

Related