Measuring execution time of a function inside linux kernel

You can use the function tracer API to get a trace of all function calls and returns, with high-precision timestamps. This includes interrupt events and context switches. You can then analyze the resulting trace in userspace to get an accurate idea of how long your function takes to run.

If you can't use the function tracer API, you could call the do_gettimeofday() call to get a microsecond-resolution timestamp, or getnstimeofday() for nanosecond resolution. These are the same functions the userspace gettimeofday() call uses internally. Of course, for very fast functions this may not be sufficient accuracy; any faster accuracy than that and you'll probably need to dig into the timer code to see how it implements cycle conversions. Note also that just because they have high resolution does not mean they have that much accuracy - but they should be useful for benchmarking purposes.

Note that any form of tracing will result in additional latency - do_gettimeofday() requires a number of atomic compare-and-swap operations, and ftrace puts logging code on every single function pre- and post-amble. You should take this into consideration when interpreting results.


I'm not sure you will obtain the result you want but we use the follwing code to have microseconds.

double Microsecs()
{
   static struct timeval _t;  
   static struct timezone tz;  
   gettimeofday(&_t, &tz);  
   return   (double)_t.tv_sec + (double)_t.tv_usec/(1000*1000);
}

Than you call it before and after the call you want and see how many time it.
We've been using this method to evaluate IO time monitoring read/write/seek operation in order to oprimize performance and we're having good results.

HTH.

Tags:

Linux Kernel