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.