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!

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Try to additionaly print out start and end time on their own. @phil
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)

4 Comments

One cast should be enough, however.
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.
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.
are you sure your code takes enough time to execute for being measurable?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.