Skip to content

Instantly share code, notes, and snippets.

@glasnt glasnt/
Created Dec 15, 2015

What would you like to do?
Get Number of CPUs for Any System, if Python is about
# Based on :
import os
def ncpus():
#for Linux, Unix and MacOS
if hasattr(os, "sysconf"):
if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
#Linux and Unix
ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
if isinstance(ncpus, int) and ncpus > 0:
return ncpus
#MacOS X
return int(os.popen2("sysctl -n hw.ncpu")[1].read())
#for Windows
if os.environ.has_key("NUMBER_OF_PROCESSORS"):
ncpus = int(os.environ["NUMBER_OF_PROCESSORS"])
if ncpus > 0:
return ncpus
#return the default value
return 1
print("CPUs: %d" % ncpus())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.