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 seconds: jiffie / hertz
1st step: get the uptime using the 1st parameter of
(uptime - (starttime / hertz)
((totaltime / hertz) / elapsedTime) * 100
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
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 (
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.
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.