On Linux, how to tell how many cores of the machine are active?

On Linux, how to tell how many cores of the machine are active? I assume a test for this would work for Android too. I need to know if more than one core is ever active. Was wondering to test this by having a process create many threads. Is it possible for a thread to query which processor it is on? that way one can tell if multiple cores will ever be used under heavy load. Not sure if I am on the right track.


Solution 1:

You can use top to list the utilization of each core. Press 1 if necessary to split the CPU row into a separate row for each core.

You can also add a column that shows the last-used core for each process. Press f to bring up the field list, then j to activate the "P" column. Then press space to return to the live view.

Solution 2:

ps has a field called psr to tell you which processor a job is running on.

So you could use something like:

ps -e -o psr= | sort | uniq | wc -l

Note that merely running ps like this will of course make at least one core active.

Probably better is to run this:

tmp=/tmp/ps.$$
ps -e -o psr= > /tmp/ps.$$
sort -u "$tmp" | wc -l
rm "$tmp"

that way the sort and wc do not increase the count.

Solution 3:

Try the following:

cat /proc/cpuinfo

Here's a link to an Android Java example.

Solution 4:

htop

This command works good in both ubuntu and centos and shows graphically how many CPUs and how are they being used.

for centos:

yum install htop

for ubuntu:

apt-get install htop

Solution 5:

You can use:

cat /sys/devices/system/cpu/possible or cat /sys/devices/system/cpu/online

Possible is mainly in case you have isolated a CPU to run some particular program.