# how-to-calculate-the-cpu-usage-in-linux

As we know, one can use top or other tools to get cpu usage。 Below is the output of top

Now I will explain how to calculate the CPU usage in Linux.

One word, the CPU usage is the percent of the time that the CPU is being used to complete tasks.

• If there is no task to run, CPU is idle;
• If CPU is doing some work, it’s busy;
• Sometime CPU is waiting for the IO operation to complete, is’s so-called iowait.

There are two kind of usage.

1. usage of host, like the third line of top output above, indicating how busy is the machine.
2. usage of task, like the output of pidstat -p <pid> or top -p <pid>, indicating how busy is the task.

This two kinds are calculated from two different methods.

## CPU usage of host

The /proc/stat show the cpu time since boot, you can read man5 proc to learn the meaning of each filed.

We can use this data to calculate the cpu usage.

We cat /proc/stat and store the content as stat1, sleep a while, cat-store again as stat2.

Usage is between 0 and 100%.

In multi process machine, we can see the cpu0, cpu1… lines, so we can get the single core usage by same method.

The /proc/<pid>/stat show the cpu time used by the task since the task was started.
For example: task pid = 1024, the path is /proc/1024/stat.
You can also read the man proc the learn the meaning of each filed.
So the cpu usage of one task is the cpu time used by the task(14 utime + 15 stime, unit is clock ticks) / the real time past (from /proc/uptime, unit is seconds).
We cat /proc/<pid>/stat and /proc/uptime, store the content as stat1 and uptime1, sleep a while, cat-store again as stat2 and uptime2.