I am trying to calculate the CPU usage of a process in Android as follows, however i am not sure if its right due to the output produced.
To convert from jiffie to
While it is true that on most Android devices the value will be 100, on some devices it could be a different value. That is because this value depends on the CPU's architecture. ARM CPUs would have 100 for the USER_HZ constant value but x86 CPUs would have 1000 as you can see here.
I suspect that you used the value in /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
as your hertz
value. This is incorrect since that file gives you the CPU hardware clock frequency, but you must use the Linux kernel clock frequency as your hertz
value.
The CPU hardware clock and Linux kernel clock are different. The Linux kernel -- which Android runs -- has its own timer (clock) which it updates at a certain frequency; the frequency at which this timer updates is the kernel hertz (HZ
) value.
For historical reasons, the clock tick values listed in Linux proc and sys files are scaled from the kernel HZ
frequency to a common frequency via the Linux kernel USER_HZ
constant. It is this USER_HZ
constant which we must use as the hertz
value in our calculations.
226.06
seconds38
clock ticks32
clock ticks13137
clock ticks100
(Linux kernel USER_HZ
constant)
total_time = utime + stime = 38 + 32 = 70
seconds = uptime - (starttime / Hertz) = 226.06 - (13137 / 100) = 94.69
cpu_usage = 100 * ((total_time / Hertz) / seconds) = 100 * ((70 / 100) / 94.69) = 0.7392...
The total CPU usage of your process is about 0.739%. If this seems small, remember that your process shares the CPU with all the other processes on the system: the majority of normal processes are idle for most of their life, so any one process will typically average a low total CPU usage.