How to Detect the Number of Physical Processors/Cores on Windows, MAC and Linux

Programmatically find the number of cores on a machine


C++11

#include <thread>

//may return 0 when not able to detect
const auto processor_count = std::thread::hardware_concurrency();

Reference: std::thread::hardware_concurrency


In C++ prior to C++11, there's no portable way. Instead, you'll need to use one or more of the following methods (guarded by appropriate #ifdef lines):

  • Win32

    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);
    int numCPU = sysinfo.dwNumberOfProcessors;
  • Linux, Solaris, AIX and Mac OS X >=10.4 (i.e. Tiger onwards)

    int numCPU = sysconf(_SC_NPROCESSORS_ONLN);
  • FreeBSD, MacOS X, NetBSD, OpenBSD, etc.

    int mib[4];
    int numCPU;
    std::size_t len = sizeof(numCPU);

    /* set the mib for hw.ncpu */
    mib[0] = CTL_HW;
    mib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU;

    /* get the number of CPUs from the system */
    sysctl(mib, 2, &numCPU, &len, NULL, 0);

    if (numCPU < 1)
    {
    mib[1] = HW_NCPU;
    sysctl(mib, 2, &numCPU, &len, NULL, 0);
    if (numCPU < 1)
    numCPU = 1;
    }
  • HPUX

    int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL);
  • IRIX

    int numCPU = sysconf(_SC_NPROC_ONLN);
  • Objective-C (Mac OS X >=10.5 or iOS)

    NSUInteger a = [[NSProcessInfo processInfo] processorCount];
    NSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];

How to discover number of *logical* cores on Mac OS X?

You can do this using the sysctl utility:

sysctl -n hw.ncpu

How to find number of physical core in a Windows system with c++ code

From https://msdn.microsoft.com/en-us/library/windows/desktop/ms724958(v=vs.85).aspx:

Note For information about the physical processors shared by logical processors, call GetLogicalProcessorInformationEx with the RelationshipType parameter set to RelationProcessorPackage (3).

You can get the related hardware of the logical processors, and infer how many physical processors are there

How to obtain the number of CPUs/cores in Linux from the command line?


grep -c ^processor /proc/cpuinfo

will count the number of lines starting with "processor" in /proc/cpuinfo

For systems with hyper-threading, you can use

grep ^cpu\\scores /proc/cpuinfo | uniq |  awk '{print $4}'

which should return (for example) 8 (whereas the command above would return 16)

How to find out the number of CPUs using python

If you're interested into the number of processors available to your current process, you have to check cpuset first. Otherwise (or if cpuset is not in use), multiprocessing.cpu_count() is the way to go in Python 2.6 and newer. The following method falls back to a couple of alternative methods in older versions of Python:

import os
import re
import subprocess


def available_cpu_count():
""" Number of available virtual or physical CPUs on this system, i.e.
user/real as output by time(1) when called with an optimally scaling
userspace-only program"""

# cpuset
# cpuset may restrict the number of *available* processors
try:
m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$',
open('/proc/self/status').read())
if m:
res = bin(int(m.group(1).replace(',', ''), 16)).count('1')
if res > 0:
return res
except IOError:
pass

# Python 2.6+
try:
import multiprocessing
return multiprocessing.cpu_count()
except (ImportError, NotImplementedError):
pass

# https://github.com/giampaolo/psutil
try:
import psutil
return psutil.cpu_count() # psutil.NUM_CPUS on old versions
except (ImportError, AttributeError):
pass

# POSIX
try:
res = int(os.sysconf('SC_NPROCESSORS_ONLN'))

if res > 0:
return res
except (AttributeError, ValueError):
pass

# Windows
try:
res = int(os.environ['NUMBER_OF_PROCESSORS'])

if res > 0:
return res
except (KeyError, ValueError):
pass

# jython
try:
from java.lang import Runtime
runtime = Runtime.getRuntime()
res = runtime.availableProcessors()
if res > 0:
return res
except ImportError:
pass

# BSD
try:
sysctl = subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
stdout=subprocess.PIPE)
scStdout = sysctl.communicate()[0]
res = int(scStdout)

if res > 0:
return res
except (OSError, ValueError):
pass

# Linux
try:
res = open('/proc/cpuinfo').read().count('processor\t:')

if res > 0:
return res
except IOError:
pass

# Solaris
try:
pseudoDevices = os.listdir('/devices/pseudo/')
res = 0
for pd in pseudoDevices:
if re.match(r'^cpuid@[0-9]+$', pd):
res += 1

if res > 0:
return res
except OSError:
pass

# Other UNIXes (heuristic)
try:
try:
dmesg = open('/var/run/dmesg.boot').read()
except IOError:
dmesgProcess = subprocess.Popen(['dmesg'], stdout=subprocess.PIPE)
dmesg = dmesgProcess.communicate()[0]

res = 0
while '\ncpu' + str(res) + ':' in dmesg:
res += 1

if res > 0:
return res
except OSError:
pass

raise Exception('Can not determine number of CPUs on this system')

Number of processors/cores in command line

nproc is what you are looking for.

More here : http://www.cyberciti.biz/faq/linux-get-number-of-cpus-core-command/

How can I get the number of CPU cores in Powershell?

Ran Turner's answer provides the crucial pointer, but can be improved in two ways:

  • The CIM cmdlets (e.g., Get-CimInstance) superseded the WMI cmdlets (e.g., Get-WmiObject) in PowerShell v3 (released in September 2012). Therefore, the WMI cmdlets should be avoided, not least because PowerShell (Core) (v6+), where all future effort will go, doesn't even have them anymore. Note that WMI still underlies the CIM cmdlets, however. For more information, see this answer.

  • Format-Table, as all Format-* cmdlets, is designed to produce for-display formatting, for the human observer, and not to output data suitable for later programmatic processing (see this answer for more information).

    • To instead create objects with a subset of the input objects' properties, use the Select-Object cmdlet. (If the output object(s) have 4 or fewer properties and aren't captured, they implicitly format as if Format-Table had been called; with 5 or more properties, it is implicit Format-List).

Therefore:

# Creates a [pscustomobject] instance with 
# .NumberOfCores and .NumberOfLogicalProcessors properties.
$cpuInfo =
Get-CimInstance –ClassName Win32_Processor |
Select-Object -Property NumberOfCores, NumberOfLogicalProcessors

# Save the values of interest in distinct variables, using a multi-assignment.
# Of course, you can also use the property values directly.
$cpuPhysicalCount, $cpuLogicalCount = $cpuInfo.NumberOfCores, $cpuInfo.NumberOfLogicalProcessors

Of course, if you're only interested in the values (CPU counts as mere numbers), you don't need the intermediate object and can omit the Select-Object call above.

As for a one-liner:

If you want a one-liner that creates distinct variables, without repeating the - costly - Get-CimInstance call, you can use an aux. variable that takes advantage of PowerShell's ability to use assignments as expressions:

$cpuPhysicalCount, $cpuLogicalCount = ($cpuInfo = Get-CimInstance -ClassName Win32_Processor).NumberOfCores, $cpuInfo.NumberOfLogicalProcessors
  • To save the numbers in distinct variables and output them (return them as a 2-element array), enclose the entire statement in (...).

  • To only output the numbers, simply omit the $cpuPhysicalCount, $cpuLogicalCount = part.

How can I query the number of physical cores from MATLAB?

You need to use the undocumented command

feature('numcores')

as explained here: http://undocumentedmatlab.com/blog/undocumented-feature-function/



Related Topics



Leave a reply



Submit