Monday 28 October 2013

[Kernel Programming #7] ktime_get() and do_gettimeofday() APIs use

We have some APIs to measure time taken for a function or a piece of code in the driver.

1. do_gettimeofday()
2. ktime_get()

These APIs are used to measure the time (absolute timestamp) in the kernel.
do_gettimeofday() gives microsecond precision.
ktime_get() return ktime_t object, which has nano second precision.

ktime_get:

===========
Here is abstract code to show how ktime_get() API will be used in our driver to measure time taken for a function.

The prototype for ktime_get is:

 #include <linux/ktime.h>
 ktime_t ktime_get(void);

Sample-code:
--------------
ktime_t start, end;
s64 actual_time;

start = ktime_get();

function();
/* or piece of code */
....
....

end = ktime_get();

actual_time = ktime_to_ns(ktime_sub(end, start));

printk(KERN_INFO, "Time taken for function() execution: %lld\n",
(long long)actual_time);

/* Use below code for millisec precision */
actual_time = ktime_to_ms(ktime_sub(end, start));

printk(KERN_INFO, "Time taken for function() execution: %u\n",
(unsigned int)actual_time);


do_gettimeofday():

==================
Here is abstract code to show how do_gettimeofday API will be used in our driver to measure time taken for a function.

The prototype for do_gettimeofday is:

 #include <linux/time.h>
 void do_gettimeofday(struct timeval *tv);

When this function called, it fills the timestamp data in struct timeval.

Using struct timeval members, we can extract seconds and microseconds info.

Sample code:
-------------
do_gettimeofday(&tstart);

/* Function or code to measure time bound */

do_gettimeofday(&tend);

printk("time taken: %ld millisec\n",
1000 * (tend.tv_sec - tstart.tv_sec) +
(tend.tv_usec - tstart.tv_usec) / 1000);

No comments:

Post a Comment

You might also like

Related Posts Plugin for WordPress, Blogger...