Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: September 2, 2024
Nowadays, most personal computers contain multiple CPU cores. This makes the processes run more efficiently.
Sometimes, it can be tricky to see how the load is spread across the cores.
In this tutorial, we’ll learn how to understand which process is run on which CPU core. Firstly, we’ll use top and htop commands for that. Secondly, we’ll look at the ps command.
Both top and htop commands provide an interactive interface with information about running processes.
By default, they don’t include the CPU core details for each running process. Let’s see how we can enable it.
To enable the CPU core details for top, we run the top command first.
After that, we press f to enter the Fields Management screen. Then, we arrow down to the line P = Last Used CPU (SMP) and toggle it on with the key d or with space.
Finally, we press q to return to the main screen. As a result, we should be able to see the P column which shows the last used CPU core per process:
$ top
...
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND P
2750 user 20 0 7160228 403680 129236 S 33,6 2,5 352:24.70 gnome-shell 2
15713 user 20 0 17156 5376 1536 S 5,6 0,0 1449:25 htop 4
As we can see, the process with PID 2750 uses the CPU core 2, while the process 15713 runs on the core 4.
To enable the same for htop, we first run the htop command. Now, we press the F2 key to enter the setup interface.
Then, using the arrows, we select the configuration Columns in the Setup column, and Processor in the Available Columns:
Finally, we press F5 to add the Processor column to the interface, and press Esc to exit to the main screen:
$ htop
...
CPU PID USER PRI NI VIRT RES SHR S CPU% MEM% TIME+ Command
2 1257 root 20 0 82772 1408 1280 S 0.0 0.0 0:00.00 /usr/sbin/irqbalance --foreground
1 1274 avahi 20 0 7496 540 384 S 0.0 0.0 0:00.00 avahi-daemon: chroot helper
...
As we can see, the first column CPU now shows the CPU core used by the process.
In case we need to get a list of all processes running for each CPU core, we can use the ps command with the grep filter:
$ CORENUM=3; ps -e -o pid,psr,cpu,cmd | grep -E "^[[:space:]][[:digit:]]+[[:space:]]+${CORENUM}"
181925 3 - bash
182519 3 - /usr/bin/seahorse --gapplication-service
Here, we get PIDs of all processes running on the CPU core 3.
Let’s look into the command in more detail:
To summarize, we can now get a list of all processes per CPU core by tweaking the CORENUM variable.
In this article, we discussed the commands to get the running processes per CPU core. First, we looked at how to get CPU core details using the top and htop commands. Then, we found out how to get a list of all processes running for each CPU core using the ps command with the grep-based filter.