Why do two CPUs work when I am only working with one process?

Viewed 92

I'm running a script like

def test0():
    start = time()
    for i in range(int(1e8)):
        i += 1
    print(time() - start)

When I run this on my machine which has 4 CPUs I get the following trace for CPU usage using the Ubuntu 20.04 system monitor.

enter image description here

In the image you can see I ran two experiments separated by some time. But in each experiment, the activity of 2 of the CPUs peaks. Why?

1 Answers

This seems normal to me. The process that is running your python code is not, at least by default, pinned to a specific core. This means that the process can be switched between different cores, which is what is happening in this case. Those spikes are not simultaneous, it indicates that the process was switched from one core to another.

On Linux, you can observe this using

watch -tdn0.5 ps -mo pid,tid,%cpu,psr -p 172810

where 172810 is PID of the python process (which you can get, for example, from the output of top)

If you want to pin the process to a particular core, you can use psutils in your code.

import psutil
p = psutil.Process()
p.cpu_affinity([0])   # pinning the process to cpu 0

Now, you should see only one core spiking. (but avoid doing this if you don't have a good reason for it).

Related