Python получить количество процессоров

Как узнать количество процессоров использующих python

Я хочу знать количество процессоров на локальной машине с помощью Python. Результат должен быть user/real в качестве вывода time(1) при вызове с оптимальным масштабированием программы только для пользовательского пространства.

Вы должны помнить о cpusets (в Linux). Если вы работаете с процессором, приведенные ниже решения по-прежнему будут указывать количество реальных процессоров в системе, а не число, доступное вашему процессу. /proc//status есть строки, в которых указано количество процессоров в текущем процессоре: ищите Cpus_allowed_list .

13 ответов

Если вас интересует количество процессоров, доступных вашему текущему процессу, вам сначала нужно проверить 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@8+$', 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') 

На MacPro 1,0 с последней версией Ubuntu, на ноутбуке HP с последней версией Debian и на старом eMachine, на котором установлена старая версия Ubuntu, результаты /proc/self/status cpus_allowed соответственно ff, f и f — соответствует 8, 4 и 4 по вашей (правильной) математике. Однако фактическое количество процессоров составляет соответственно 4, 2 и 1. Я считаю, что подсчет числа появлений слова «процессор» в /proc/cpuinfo может быть лучшим способом. (Или у меня вопрос неправильный?)

Читайте также:  Functions if else javascript

С некоторыми дальнейшими исследованиями — если это можно сказать о «поиске в Google» — я нашел из использования /proc/cpuinfo что если для любого из списков для каждого «процессора» вы умножаете «братьев и сестер» на «процессорные ядра» вы получите ваш номер «Cpus_allowed». И я понимаю, что братья и сестры относятся к гиперпоточности, отсюда ваша ссылка на «виртуальную». Но факт остается фактом: ваше число «Cpus_allowed» равно 8 на моем MacPro, тогда как ваш ответ multiprocessing.cpu_count() равен 4. Мой собственный метод open(‘/proc/cpuinfo’).read().count(‘processor’) также производит 4, количество физических ядер (два двухъядерных процессора).

open(‘/proc/self/status’).read() забывает закрыть файл. Вместо этого используйте with open(‘/proc/self/status’) as f: f.read()

Источник

Number of CPUs in Python

You can determine the number of CPUs in your system using the multiprocessing.cpu_count() function or the os.cpu_count() function.

In this tutorial you will discover how to count the number of CPUs in Python.

Need to Know The Number of CPUs

In concurrent programming, we often need to know the number of CPUs available to the program.

There are many reasons for this, such as:

  • Configuring a thread pool or a process pool.
  • Configuring the number of concurrent tasks.
  • Estimating the time a program will take to run.

How can we determine the number of CPU cores from within the program?

Run your loops using all CPUs, download my FREE book to learn how.

What Do We Mean By CPU

Before we look at how to determine the number of CPU cores in a program, let’s get clear on what we mean by a CPU and a core and the difference between physical cores and logical cores.

CPU vs Core

A central processing unit or simply “processor” or “CPU” is a chip in the computer that executes instructions.

Traditionally, we had one CPU in the computer, perhaps with a math coprocessor.

  • CPU: Central processing unit, a chip within the computer for executing instructions.
Читайте также:  Java parsing web pages

A core is another name for a physical CPU for executing instructions.

A computer with multiple CPUs is referred to as having multiple cores.

Similarly, a computer chip that has multiple CPUs within it, is referred to as a multi-core processor.

As such, as developers, the terms “CPUs” and “cores” are used interchangeably. We might even refer to them as “CPU cores”.

Almost all modern computers have multiple cores.

Physical vs Logical CPUs

There is one further wrinkle.

Modern CPUs typically make use of a technology called hyperthreading.

Hyperthreading does not refer to a program using threads. Instead, it refers to a technology within the CPU cores themselves that allows each physical core or CPU to act as if it were two logical cores or two CPUs.

  • Physical Cores: The number of CPU cores provided in the hardware, e.g. the chips.
  • Logical Cores: The number of CPU cores after hyperthreading is taken into account.

It provides automatic in-core parallelism that can offer up to a 30% speed-up over CPU cores that do not offer the technology.

As such, when we count CPU cores in a system, we typically count the number of logical CPU cores, not the number of physical CPU cores.

If you know your system uses hyperthreading (it probably does), then you can get the number of physical CPUs in your system by dividing the number of logical CPUs by two.

Next, let’s look at how we can get the number of CPUs in Python.

Confused by the multiprocessing module API?
Download my FREE PDF cheat sheet

How to Get The Number of CPUs in Python

There are a number of ways to get the number of CPUs in Python.

The two pure Python approaches provided by the standard library are:

  • multiprocessing.cpu_count() function
  • os.cpu_count() function.

Let’s take a closer look at each in turn.

How to Use multiprocessing.cpu_count

We can get the count of the number of logical CPU cores in the current system using the multiprocessing.cpu_count() function.

It returns a positive integer.

Источник

Python получить количество процессоров

  • Python | os.ctermid() method
  • Python | os.environ object
  • Python os.chdir() method
  • Python | os.fchdir() method
  • Python | os.getcwd() method
  • Python | os.getenv() method
  • Python | os.get_exec_path() method
  • Python | os.geteuid() and seteuid() method
  • Python | os.getgrouplist() method
  • Python | os.getgroups() method
  • Python | os.getlogin() method
  • Python | os.getpgid() method
  • Python | os.getpgrp() method
  • Python | os.getpid() method
  • Python | os.getppid() method
  • Python | os.getresuid() and os.setresuid() method
  • Python | os.getuid() and os.setuid() method
  • Python | os.setregid() method
  • Python | os.setreuid() method
  • Python | os.setgroups() method
  • Python | os.getsid() method
  • Python | os.strerror() method
  • Python | os.supports_bytes_environ object
  • Python | os.umask() method
  • Python | os.link() method
  • Python | os.listdir() method
  • Python | os.mkdir() method
  • Python | os.makedirs() method
  • Python | os.mkfifo() method
  • Python | os.major() method
  • Python | os.minor() method
  • Python | os.makedev() method
  • Python | os.readlink() method
  • Python | os.remove() method
  • Python | os.removedirs() method
  • Python | os.rename() method
  • Python | os.renames() method
  • Python – os.replace() method
  • Python | os.rmdir() method
  • Python | os.scandir() method
  • Python | os.stat() method
  • Python | os.statvfs() method
  • Python | os.sync() method
  • Python | os.truncate() method
  • Python | os.unlink() method
  • os.walk() in Python
  • Python | os.cpu_count() method
  • Python | os.abort() method
  • Python | os._exit() method
  • Python | os.fork() method
  • Python | os.kill() method
  • Python | os.nice() method
  • Python | os.system() method
  • Python | os.times() method
  • Python | os.wait() method
  • Python | os.cpu_count() method
  • Python | os.open() method
  • Python | os.get_blocking() method
  • Python | os.isatty() method
  • Python | os.openpty() method
  • Python | os.pipe() method
  • Python | os.pipe2() method
  • Python | os.pread() method
  • Python | os.write() method
  • Python | os.pwrite() method
  • Python | os.read() method
  • Python | os.sendfile() method
  • Python | os.set_blocking() method
  • Python | os.ctermid() method
  • Python | os.environ object
  • Python os.chdir() method
  • Python | os.fchdir() method
  • Python | os.getcwd() method
  • Python | os.getenv() method
  • Python | os.get_exec_path() method
  • Python | os.geteuid() and seteuid() method
  • Python | os.getgrouplist() method
  • Python | os.getgroups() method
  • Python | os.getlogin() method
  • Python | os.getpgid() method
  • Python | os.getpgrp() method
  • Python | os.getpid() method
  • Python | os.getppid() method
  • Python | os.getresuid() and os.setresuid() method
  • Python | os.getuid() and os.setuid() method
  • Python | os.setregid() method
  • Python | os.setreuid() method
  • Python | os.setgroups() method
  • Python | os.getsid() method
  • Python | os.strerror() method
  • Python | os.supports_bytes_environ object
  • Python | os.umask() method
  • Python | os.link() method
  • Python | os.listdir() method
  • Python | os.mkdir() method
  • Python | os.makedirs() method
  • Python | os.mkfifo() method
  • Python | os.major() method
  • Python | os.minor() method
  • Python | os.makedev() method
  • Python | os.readlink() method
  • Python | os.remove() method
  • Python | os.removedirs() method
  • Python | os.rename() method
  • Python | os.renames() method
  • Python – os.replace() method
  • Python | os.rmdir() method
  • Python | os.scandir() method
  • Python | os.stat() method
  • Python | os.statvfs() method
  • Python | os.sync() method
  • Python | os.truncate() method
  • Python | os.unlink() method
  • os.walk() in Python
  • Python | os.cpu_count() method
  • Python | os.abort() method
  • Python | os._exit() method
  • Python | os.fork() method
  • Python | os.kill() method
  • Python | os.nice() method
  • Python | os.system() method
  • Python | os.times() method
  • Python | os.wait() method
  • Python | os.cpu_count() method
  • Python | os.open() method
  • Python | os.get_blocking() method
  • Python | os.isatty() method
  • Python | os.openpty() method
  • Python | os.pipe() method
  • Python | os.pipe2() method
  • Python | os.pread() method
  • Python | os.write() method
  • Python | os.pwrite() method
  • Python | os.read() method
  • Python | os.sendfile() method
  • Python | os.set_blocking() method
Читайте также:  Add function to object python

Источник

Оцените статью