2

I finished the programming of a class project, but I still need to get the running time. I tried clock() function, but it didn't work.

int main()
{
  clock_t start_time=clock();
  (my codes)
  clock_t end_time=clock();
  printf("The running time is %f", end_time-start_time);
}

I guess this is the right way to use clock function, am I right? But I got nothing but 0.000000. Could someone tell me the right way? Thank you!

Slim
  • 1,708
  • 5
  • 37
  • 60
phil
  • 255
  • 4
  • 16

2 Answers2

2

clock_t is not a float, but an integer type, most probably a long.

So you might use %ld to printf() it.


Also clock() does not return seconds, but CPU ticks. So to get seconds the value returned by clock() shall be devided by the system constant CLOCKS_PER_SEC.

alk
  • 69,737
  • 10
  • 105
  • 255
  • Thanks. But I still get 0. I guess it should work, since I've read some related posts, some other people also say it works this way. I don't know why it fails in my code. Actually my code still has glitches, I've been trying to figure them out. – phil Nov 16 '12 at 19:23
  • Try to additionaly print out start and end time on their own. @phil – alk Nov 16 '12 at 19:29
0

phil you did in the right way (maybe you should also divide by CLOCKS_PER_SEC)

   float time = (float)(end_time-start_time)/(float)CLOCKS_PER_SEC;
   printf("The running time is %f", time);

and don't forget to cast as "float" because if you have as result 0.5 it will be rounded down to 0.0 because of integer division.

After that how much time takes you program to execute? because as far as I know, clock has a capability of measuring time of few milliseconds, so if you program takes less time than few milliseconds, it is likely to not detect this time (clock is very good for measuring times of several seconds with relatively good precision)

CoffeDeveloper
  • 7,961
  • 3
  • 35
  • 69
  • One cast should be enough, however. – glglgl Nov 16 '12 at 15:11
  • absolutely correct, but I usually explicitly write all the required casts. More clear for users and good practice too. Many reasons for doing that. probably there is lot of discussions about that. – CoffeDeveloper Nov 16 '12 at 15:25
  • Thanks. But I still get 0. I guess it should work, since I've read some related posts, some other people also say it works this way. I don't know why it fails in my code. Actually my code still has glitches, I've been trying to figure them out. – phil Nov 16 '12 at 19:23
  • are you sure your code takes enough time to execute for being measurable? – CoffeDeveloper Nov 26 '12 at 23:19