CPU Usage Percent – Python One-Liner for Load Average per CPU

Processor usage is 88%. But how do I get a number like this?
For gurus, this Python one-liner prints CPU usage

$ python3 -c "print('{:.0f}%'.format( float('$(cat /proc/loadavg)'.split()[0]) / float('$(nproc)')*100 ) )"
12%

The rest of us can read on how this works. Also, we can learn how to read system state from plain text files and understand load averages.

Plain Text System Info in /proc/ and /sys

Virtual filesystems /proc/ and /sys/ contain real time information about system state. And they are plain text.

$ cat /proc/loadavg
0.40 0.53 0.45 1/664 13424

Manual pages explain how this works

~$ man proc|grep -A 3 loadavg
 /proc/loadavg
 The first three fields in this file are load average figures [...] averaged over 1, 5, and 15 minutes. [...]

Many commands get their information from /proc/ and /sys/. For example, ‘uptime’ and ‘top’ show load averages.

You Have Multiple CPUs

Typical computers have multiple CPU cores. In practice, they have multiple processors on a single chip.
$ nproc
4
This one has 4 CPUs.

Load per CPU

When load level is equal to number of processors, the CPU is fully utilized. For this computer, load average of 4.0 means 100% load.
To get any load, simply divide load with the number of CPUs.

$ cat /proc/loadavg
0.44 0.41 0.41 1/662 13809
$ nproc
4

So one minute load percentage is load 0.44 divided by CPU count 4.

$ python -c 'print(0.44/4)'
0.11

Percent means parts of hunderd, e.g. x% = x/100. Thus,  0.11 is 11%.
When there is more work than the CPU can do, there are queues. For a load percent of 120%, we would need a CPU 20% faster than we have to handle it without queues.

One Liners with Python and Bash together

As you can see, this calculation is easiest to write as a normal program. But sometimes one-liners are so convenient. For example, you could use them for your statusbar in tmux or screen.
To quickly slurp files (read them in single command), you can combine bash and Python. We execute bash subshell with $() and use the result in Python.

$ python3 -c "print('$(cat /proc/loadavg)')"
0.15 0.23 0.32 1/660 14221

Obviously, Python can count

$ python3 -c 'print(2**3)'
8

For calculations, strings must be cast to numbers

$ python3 -c 'print("123.1"*2)' # wrong
123.1123.1 # wrong
$ python3 -c 'print(float("123.1")*2)'
246.2

We can use new format() strings to round numbers

$ python3 -c 'print( "Pi is about {:.2f}".format(3.141592653589793) )'
Pi is about 3.14

Finally, put all together

$ python3 -c "print('{:.0f}%'.format( float('$(cat /proc/loadavg)'.split()[0]) / float('$(nproc)')*100 ) )"
12%

Well done.

$ python3 -c 'print("What kind of Python one-liners could you write?")'
What kind of Python one-liners could you write?
Posted in Uncategorized | Tagged , , , , , , , , , , | Comments Off on CPU Usage Percent – Python One-Liner for Load Average per CPU

Comments are closed.