Skip to content

Instantly share code, notes, and snippets.

@glasnt
Last active November 15, 2020 21:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glasnt/da797a71c34939301217 to your computer and use it in GitHub Desktop.
Save glasnt/da797a71c34939301217 to your computer and use it in GitHub Desktop.
Get Number of CPUs for Any System, if Python is about
# Based on : https://groups.google.com/d/msg/sage-devel/1lIJ961gV_w/y-2uqPCyzUMJ
import os
def ncpus():
#for Linux, Unix and MacOS
if hasattr(os, "sysconf"):
if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
#Linux and Unix
ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
if isinstance(ncpus, int) and ncpus > 0:
return ncpus
else:
#MacOS X
return int(os.popen2("sysctl -n hw.ncpu")[1].read())
#for Windows
if "NUMBER_OF_PROCESSORS" in os.environ:
ncpus = int(os.environ["NUMBER_OF_PROCESSORS"])
if ncpus > 0:
return ncpus
#return the default value
return 1
print("CPUs: %d" % ncpus())
@glasnt
Copy link
Author

glasnt commented Nov 15, 2020

I've made the suggested changes. I'm glad you found the script useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment