문제

Python을 사용하여 로컬 기계의 CPU 수를 알고 싶습니다. 결과는 있어야합니다 user/real 출력으로 time(1) 최적의 스케일링 사용자 공간 전용 프로그램으로 호출 할 때.

도움이 되었습니까?

해결책 2

프로세서 수에 관심이 있다면 사용 가능 현재 프로세스에는 확인해야합니다 CPUSET 첫 번째. 그렇지 않으면 (또는 CPUSET을 사용하지 않는 경우), multiprocessing.cpu_count() Python 2.6과 새로운 방법입니다. 다음 방법은 이전 버전의 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')

다른 팁

버전이있는 Python이 있으면> = 2.6을 사용하면 간단히 사용할 수 있습니다.

import multiprocessing

multiprocessing.cpu_count()

http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count

또 다른 옵션은 psutil 이러한 상황에서 항상 유용한 도서관 :

>>> import psutil
>>> psutil.cpu_count()
2

이것은 지원되는 모든 플랫폼에서 작동해야합니다 psutil(유닉스와 창).

어떤 경우에도 주목하십시오 multiprocessing.cpu_count 올릴 수 있습니다 NotImplementedError 동안 psutil CPU 수를 얻을 수 있습니다. 이것은 단순히 때문입니다 psutil 먼저 사용 된 것과 동일한 기술을 사용하려고합니다 multiprocessing 그리고 실패하면 다른 기술도 사용합니다.

Python 3.4+에서 : os.cpu_count ().

multiprocessing.cpu_count() 이 기능 측면에서 구현되지만 제기됩니다 NotImplementedError 만약에 os.cpu_count() 보고 None ( "CPU 수를 결정할 수 없습니다").

import os

print(os.cpu_count())

플랫폼 독립 :

psutil.cpu_count (logical = false)

https://github.com/giampaolo/psutil/blob/master/install.rst

multiprocessing.cpu_count() 논리 CPU의 수를 반환하므로 하이퍼 스레딩이있는 쿼드 코어 CPU가 있으면 반환됩니다. 8. 물리적 CPU의 수를 원한다면 HWLOC에 Python 바인딩을 사용하십시오.

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

HWLOC는 OS 및 아키텍처에서 휴대용으로 설계되었습니다.

len(os.sched_getaffinity(0)) 당신이 일반적으로 원하는 것입니다

https://docs.python.org/3/library/os.html#os.sched_getaffinity

os.sched_getaffinity(0) (Python 3에 추가) sched_setaffinity 리눅스 시스템 호출, 어떤 CPU 프로세스와 어린이가 달릴 수 있는지 제한합니다.

0 현재 프로세스의 값을 얻는 것을 의미합니다. 함수는 a set() 허용 된 CPU의 필요성 len().

multiprocessing.cpu_count() 반면에 총 물리적 CPU 수를 반환합니다.

다음과 같은 특정 클러스터 관리 시스템이기 때문에 차이는 특히 중요합니다. 플랫폼 LSF 작업 CPU 사용을 제한하십시오 sched_getaffinity.

따라서 사용하는 경우 multiprocessing.cpu_count(), 스크립트는 사용 가능한 것보다 더 많은 코어를 사용하려고 시도하여 과부하 및 시간 초과로 이어질 수 있습니다.

우리는 친화력을 taskset 공익사업.

예를 들어, 16 개의 핵심 시스템에서 Python을 1 코어 (Core 0)로 제한하는 경우 :

taskset -c 0 ./main.py

테스트 스크립트 :

main.py

#!/usr/bin/env python3

import multiprocessing
import os

print(multiprocessing.cpu_count())
print(len(os.sched_getaffinity(0)))

그런 다음 출력은 다음과 같습니다.

16
1

nproc 기본적으로 친화력을 존중합니다.

taskset -c 0 nproc

출력 :

1

그리고 man nproc 그것을 매우 명확하게 만듭니다.

사용 가능한 처리 장치 수를 인쇄하십시오

nproc has the --all 물리적 CPU 수를 얻으려는 덜 일반적인 사례에 대한 플래그 :

taskset -c 0 nproc --all

이 방법의 유일한 단점은 이것이 Unix만으로 보인다는 것입니다. 나는 Windows가 비슷한 친화력 API를 가져야한다고 생각했다. SetProcessAffinityMask, 왜 그것이 포팅되지 않았는지 궁금합니다. 그러나 나는 Windows에 대해 아무것도 모른다.

우분투 16.04, 파이썬 3.5.2에서 테스트.

코드에 추가하거나 메시지에 답장하는 방법을 알 수는 없지만 여기에는 포기하기 전에 다음과 같은 Jython에 대한 지원이 있습니다.

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

이 목적으로 "joblib"을 사용할 수도 있습니다.

import joblib
print joblib.cpu_count()

이 방법은 시스템의 CPU 수를 제공합니다. 그러나 joblib는 설치해야합니다. joblib에 대한 자세한 내용은 여기를 참조하십시오 https://pythonhosted.org/joblib/parallel.html

또는 Python의 Numexpr 패키지를 사용할 수 있습니다. 시스템 CPU에 대한 정보를 얻는 데 도움이되는 간단한 기능이 많이 있습니다.

import numexpr as ne
print ne.detect_number_of_cores()

이것들은 당신에게 하이퍼 스레드 CPU 수를 제공합니다

  1. multiprocessing.cpu_count()
  2. os.cpu_count()

이들은 가상 기계 CPU 수를 제공합니다

  1. psutil.cpu_count()
  2. numexpr.detect_number_of_cores()

VM에서 일하는 경우에만 문제가 있습니다.

Python 2.6이없는 경우 다른 옵션 :

import commands
n = commands.getoutput("grep -c processor /proc/cpuinfo")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top