I need to time my C program inside the program itself (as I am timing multiple subsections of the code and outputting their time). It must be done with (at least) millisecond accuracy. My understanding is that “time.h” functions only work to the second. Is there another way to do this?
Share
You can use the function
clock()from<time.h>:You divide the return value by the macro
CLOCKS_PER_SECto get a time amount in seconds, and if you wanted the time in milliseconds you could multiply the value by 1000, ie:Or more accurately, have a start and end
clock_tand then calculate the difference:EDIT: Just thought I’d add, a common value for
CLOCKS_PER_SECis1000000, meaning that the value returned byclock()would be a one-hundred-thousandth of a second. Therefore it’s accurate to one one-thousandth of a millisecond (a microsecond).