Calling times() in kernel space

╄→гoц情女王★ 提交于 2019-12-13 16:08:46

问题


I am developing a kernel module, and I need to get an approximate value of the CPU time consumed by some process (iterating the processes is not an issue). Specifically, I want the same behavior provided by the libc clock or the times syscall. I tried calling do_sys_times but seems it's not exported (undefined symbol when compiled).

Is there a way to call times inside a kernel module? Are there any other alternatives?


回答1:


If you want precisely measure times between some events in kernel (like context switching), you need some tracer, like SystemTap. From kernel module you may directly bind probes through various tracing and profiling subsystems like ftrace, perf or kprobes.

Here is an example which dumps message to kernel log when context is switched:

#include <linux/sched.h>
#include <linux/module.h>
#include <linux/printk.h>
#include <linux/tracepoint.h>

#include <trace/events/sched.h>

...

void my_sched_switch_probe(void* ignore, struct task_struct* prev, struct task_struct* next) {
    printk("my_sched_switch_probe: %s -> %s at %lu\n", prev->comm, next->comm, 
        (unsigned long) sched_clock());
}

int cswtracer_init(void) {
    register_trace_sched_switch(my_sched_switch_probe, NULL);

    return 0;
}

void cswtracer_fini(void) {
    unregister_trace_sched_switch(my_sched_switch_probe, NULL);
}

module_init(cswtracer_init);
module_exit(cswtracer_fini);

NOTE: do not run it, it will slow your system dramatically.

So analyze name of processes in my_sched_switch_probe() and calculate difference between time when process entered CPU (next->comm == "myprocessname") and when it leaves CPU (prev->comm == "myprocessname"). That difference is the last time period process spent on CPU during.



来源:https://stackoverflow.com/questions/29503262/calling-times-in-kernel-space

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!