Home > Net >  How to measure the execution time of a function in Linux kernel Module?
How to measure the execution time of a function in Linux kernel Module?

Time:10-29

I have a question about measuring the execution time of a function. I normally use gettimeofday(), however, this function has been removed. I see that there are 2 functions: ktime_get_ns()/ktime_get_ms() I tried to apply on my code, as below:

#include <linux/ktime.h>
...
ktime_t start_time, stop_time;
s64  elapsedTime;
start_time = ktime_get_ns();
    for_each_process() {}//My function
stop_time = ktime_get_ns();
    elapsedTime = ktime_sub(stop_time, start_time);
pr_info("elapsedTime : %u\n",(unsigned int)elapsedTime);

My output:

elapsedTime: 6

But I do not know this elapsedTime is correct or not, is it 6 nanoseconds? Could somebody review and support me?

CodePudding user response:

You are mixing up the return types.

ktime_get_ns() returns the time as a u64, not as a ktime_t structure, so you should not use it with ktime_sub(). Also, the return type of ktime_sub() is a ktime_t struct so you should use that and not s64, even if it's the same under the hood.

You have two options here depending on what you want to do, either use ktime_t structures everywhere (with the correct functions):

#include <linux/ktime.h>
...
ktime_t start_time, stop_time, elapsed_time;
start_time = ktime_get();
    for_each_process() {}//My function
stop_time = ktime_get();
elapsed_time= ktime_sub(stop_time, start_time);
pr_info("elapsedTime : %lld\n",  ktime_to_ns(elapsed_time));

Or just use u64:

#include <linux/ktime.h>
...
u64 start_time, stop_time, elapsed_time;
start_time = ktime_get_ns();
    for_each_process() {}//My function
stop_time = ktime_get_ns();
elapsedTime = stop_time - start_time;
pr_info("elapsedTime : %llu\n", elapsed_time);
  • Related