DEV Community

BC
BC

Posted on

How to know number of tasks can run in parallel in Linux and MacOS

I want to know the CPU cores & threads count, so that I could know how many tasks my computer can run in parallel. This number could later be used for specifying the pool size when creating a threading pool.

To get this count, the formula is:

num_of_cpu * cores_per_cpu * threads_per_core
Enter fullscreen mode Exit fullscreen mode

For example, if you have 1 cpu, and it has 2 cores, and each core enabled hyperthreading, so the final result might be 1 * 2 * 2 = 4

Linux

We get use lscpu to get a brief result:

$ lscpu
...
CPU(s):              4
Thread(s) per core:  1
...
Enter fullscreen mode Exit fullscreen mode

Or we could use 3 separate commands to get more info:

$ cat /proc/cpuinfo | grep "physical id"| sort | uniq | wc -l
4
$ cat /proc/cpuinfo | grep "cores" | uniq
cpu cores : 1
$ cat /proc/cpuinfo | grep "processor"| wc -l
4
Enter fullscreen mode Exit fullscreen mode

So in this machine, we have 4 cpu, each cpu has 1 core, there is no hyperthreading enabled, because the processor count is 4. Otherwise, the processor count should be greater than 4.

The number of tasks can run parallel for this computer is 4 * 1 * 1 = 4

MacOS

If you go to "About This Mac > System Report", you will be able to see some information about CPU. It looks like something like this:

system info

From here we can see the number of CPU is 1, the Cores_Per_CPU is 2, but it doesn't show how many threads for one core, i.e. if the hyperthreading is enabled.

If we open terminal and use command:

$ sysctl hw.physicalcpu hw.logicalcpu
hw.physicalcpu: 2
hw.logicalcpu: 4
Enter fullscreen mode Exit fullscreen mode

Or we can use:

$ sysctl -a | grep machdep.cpu | grep count
machdep.cpu.core_count: 2
machdep.cpu.thread_count: 4
Enter fullscreen mode Exit fullscreen mode

Now you can see the core_count is 2, and thread_count is 4, means threads_per_core is 2 (hyperthreading is enabled).

The number of tasks can run parallel for this computer is 1 * 2 * 2 = 4

Top comments (1)

Collapse
 
ac000 profile image
Andrew Clayton

On Linux at least, you can also get this at run-time from C (and I dare say other languages) with get_nprocs(3) and/or sysconf(3) with the _SC_NPROCESSORS_ONLN variable.