In the time.c file, we can find a simple example exemplifying how the preceding functions work:
- As the first step, we declare a utility function to get the execution time in nanoseconds, of a line of code:
#define print_time(str, code) \
do { \
u64 t0, t1; \
t0 = ktime_get_real_ns(); \
code; \
t1 = ktime_get_real_ns(); \
pr_info(str " -> %lluns\n", t1 - t0); \
} while (0)
This is an easy trick to define a macro that executes a line of code while taking its execution time by using the ktime_get_real_ns() function, which returns the current system time in nanoseconds.
For further information regarding ktime_get_real_ns() and related functions, you can take a look at https://www.kernel.org/doc/html/latest/core-api/timekeeping.html.
- Now, for the module's init() function, we can use our macro and then call all the preceding delaying functions as follows:
static int __init time_init(void)
{
pr_info("*delay() functions:\n");
print_time("10ns", ndelay(10));
print_time("10000ns", udelay(10));
print_time("10000000ns", mdelay(10));
pr_info("*sleep() functions:\n");
print_time("10000ns", usleep_range(10, 10));
print_time("10000000ns", msleep(10));
print_time("10000000ns", msleep_interruptible(10));
print_time("10000000000ns", ssleep(10));
return -EINVAL;
}