How to get number of cores in Python script

I am using tasks.Parallel.ForEach(pieces, helper) that I copied from the Grasshopper code to speed up Python when processing a mesh with 2.2M vertices. In order to minimize thread overhead, I divide the data into n pieces where n is the number of threads on my computer. But n is not fixed since I use my laptop (n = 8) when traveling, like now in NYC, and my tower computer (n = 36) when at home in Portland, OR.

My question is, how do I get the number of cores or threads from within a Python script?

I tried:
import os
print os.sysconf(“SC_NPROCESSORS_ONLN”)
but sysconf is not recognized.

I tried:
import multiprocessing
print ‘count =’, multiprocessing.cpu_count()
but import does not find multiprocessing.

I know Holomark shows the number of threads in its summary, but I have not located its source code in order to discover how it obtains this information.

Thanks in advance for your help.

I think there’s a typo there…

You can access this in .NET with

import System
count = System.Environment.ProcessorCount
print count
1 Like

Its all Greek to me. I cut and pasted a solution someone found into python to give it a try. It does not get past the sysconf reference so the contents of the string may be unimportant. I tried:
print os.sysconf(“SC_NPROCESSORS_ONLY”) but this failed in the same way.

Thanks for the suggestion.


Perfect. I ended up using:

from System import Environment
threads = Environment.ProcessorCount
print threads

It returns the number of logical cores = cores x threads/core which is what I want for dividing up the work.