4

I am writing a little python script to test some stuff. later I want to use it to create resource usage plots with gnuplot, but first a few tests.

The script looks like

import subprocess

result = subprocess.check_output("top -b -n 1 -c", shell=True).split("\n")

head = result[:5]
body = [x for x in result[7:] if x] #removes empty strings

for line in head:
    print line

csum = 0.0
for line in body:
    print line
    csum += float(line.split()[8])

print "CPU usage of all processes added up", csum, "%"

Running it multiple times almost always resulted in a shown CPU usage > 100%. Sometimes even > 200%. How can this be?

It runs in a virtual machine (virtualbox, ubuntu 14.04 64 bit) with two cores. The host also has two cores.

Shouldn't the sum of the usage values of all running processes be always lower than 100%? I am running htop at the same time and this shows me about 50% load on every core....

Could the problem be that maybe some processes started others and both are shown in the output of top while the parent process also shows the cpu usage of the child? ==> child gets counted twice?

Simon Hessner
  • 1,757
  • 1
  • 22
  • 49
  • 2
    Usually this usage means 100% for 1 core; if you have 2 cores it should go up to 200%. If you have slightly more it might be due to rounding or sampling artefacts. – Francis Colas Apr 06 '15 at 18:28
  • Okay, thanks. So dividing the sum by the number of cores should be correct if I want to see the "real" usage – Simon Hessner Apr 06 '15 at 18:44

2 Answers2

12

a 100% cpu is a full utilization of 1 CPU/CORE/Thread. If you have, 8 CPU, then the maximum will be 800%.

If you have thread, the story is a bit more complicated, since a thread is not a real CPU, but, on Linux it is counted as a CPU.

Breno Leitão
  • 3,487
  • 2
  • 19
  • 23
  • 4
    Showing each CPU as 100% is known in `top` as "[IRIX mode](http://stackoverflow.com/questions/14579124/why-does-whiletrue-without-thread-sleep-cause-100-cpu-usage-on-linux-but)". It can be disabled to show each of 8 CPUs as 12.5% – that other guy Apr 06 '15 at 18:35
  • Okay... Good to know :) Now I understand. – Simon Hessner Apr 06 '15 at 18:46
  • Is there a better way to find out the CPU usage of a few specific processes? I mean other than parsing the output of top – Simon Hessner Apr 06 '15 at 18:47
  • Yes, there is. you can use top -p {the process id which you want to monitor} – buqing Aug 15 '16 at 18:37
3

In my experience I had an oversized SQL database that was causing problems. This was because it caused the mysqld (mysql daemon) to execute at over the capacity of the system memory causing the server to crash. When i tried the 'top' command in UNIX the system showed that the process was using over 100% of memory. Thus processes can utilise more than 100% of system memory.