0

Could anyone point out how I can calculate the cpu usage of a specific process in percentage terms? The code is a kernel module so I am looking for a better way than to parse data from /proc or to use a system call. I was wondering if I could calculate it using a combination of task_struct and linux kernel functions.

Pedram Esmaeeli
  • 174
  • 2
  • 11

1 Answers1

1

task_struct have user time (utime), system time (stime), start_time and ..., here is the algorithm in https://stackoverflow.com/a/16736599/4490542

Community
  • 1
  • 1
e.jahandar
  • 1,715
  • 12
  • 30
  • 1
    Most of the difficulty was for finding the exact functions to use, in order to find the equivalent information of what is found in /proc directory. especially the elapsed time and and the conversion of units. This piece of [source code](http://lxr.free-electrons.com/source/kernel/tsacct.c#L29) helped a lot. But still one problem remains. Upon casting long to float in order to calculate percentage, I get the error: "error: SSE register return with SSE disabled" – Pedram Esmaeeli Dec 17 '16 at 09:49
  • 1
    @PedramEsmaeeli There is no direct way obtaining cpu load of a process, even userspace applications use these parameters to calculate, see line 955 https://github.com/hishamhm/htop/blob/e0209da88faf3b390d71ff174065abd407abfdfd/ProcessList.c , but the problem is floating point calculations in kernel space (the error you mentioned), floating point in kernel isn't easy. look at crypto core of kernel, there is software fpu there – e.jahandar Dec 17 '16 at 10:01