clock time in milliseconds into a c program

Ryan Sommers ryans at gamersimpact.com
Wed Jan 19 18:12:05 PST 2005


Marco Trentini wrote:
> Hi, I need to clock the function execution time into a C
> program. I know /usr/include/time.h library but I need to
> clock the time in milliseconds.
> 
> Any suggestions, links?
> 

Are you looking for how long the processor spent executing your code? Or 
the difference in wall time between when it enters the function and when 
it exits the function?

The difference will be subtle, but will still be there. The problem with 
using wall time (the amount of time elapsed on the clock on the wall) is 
that it doesn't factor in context switches. In 1 second of wall time 
your code might only have been executing for a very small piece of it. 
Other programs could have been scheduled to run, the kernel could be 
doing a lot of system maintenance, all will eat time slices, and none 
will be shown if you just just look at the wall clock time.

However, if all you want if to look at where a bottleneck is, or how 
long your program is spending in a given function, you could just 
generate a profile.

It might be useful to know if you are looking for wall time or CPU time 
spent in those functions.

At any rate, I'd suggest looking at microtime or nanotime. the (struct 
timeval) that microtime uses is defined in /usr/include/sys/_timeval.h 
if I remember.

There are a lot of good guides to time keeping and accuracies. You might 
check out http://people.freebsd.org/~phk/ I remember him having a 
section on his timekeeping hobbies.


-- 
Ryan Sommers
ryans at gamersimpact.com


More information about the freebsd-hackers mailing list