Python: Cross-platform solution to detect physical

2019-07-20 00:34发布

I'm trying to detect the number of non-HyperThreading cores on a machine using a cross-platform method.

Multiprocessing's cpu_count only detects the total number of processors, and I can grep /proc/cpuinfo on Linux machines to find the answer. However, I'm looking for a Windows solution.

This newsgroup thread helped a little, but I still haven't found the answer.

3条回答
地球回转人心会变
2楼-- · 2019-07-20 00:45

You can use Tim Golden's WMI bindings to access wmi information about CPUs on Windows. See Tim's wmi module cookbook. You probabably want to use the Win32_Processor class -- see the Microsoft documentation.

Note that in the remarks section the Microsoft documentation states:

To determine if hyperthreading is enabled for the processor, compare NumberOfLogicalProcessors and NumberOfCores. If hyperthreading is enabled in the BIOS for the processor, then NumberOfCores is less than NumberOfLogicalProcessors. For example, a dual-processor system that contains two processors enabled for hyperthreading can run four threads or programs or simultaneously. In this case, NumberOfCores is 2 and NumberOfLogicalProcessors is 4.

Dag Wieer's blog shows a way of extracting hyperthreading info from /proc/cpuinfo on Linux.

I think, if the output of the first and second lines of

cat /proc/cpuinfo | egrep 'physical|processor' | grep -v sizes | \
                    tail -n2 | cut -d : -f 2`

is different, hyperthreading is enabled.

查看更多
贼婆χ
3楼-- · 2019-07-20 00:53

platform independent and in python standard library:

psutil.cpu_count(logical=False)

查看更多
我只想做你的唯一
4楼-- · 2019-07-20 00:56

For a platform-independent method, see the python bindings to hwloc:

#!/usr/bin/env python
import hwloc
topology = hwloc.Topology()
topology.load()
print topology.get_nbobjs_by_type(hwloc.OBJ_CORE)

hwloc is designed to be portable across OSes and architectures.

查看更多
登录 后发表回答