How to how to know the number of CPu using python (Python Programing Language)

Available Answers: 1

Answer #1#
Columbus, United States
1
import os
2
import re
3
import subprocess
4
5
6
def available_cpu_count():
7
    """ Number of available virtual or physical CPUs on this system, i.e.
8
    user/real as output by time(1) when called with an optimally scaling
9
    userspace-only program"""
10
11
    # cpuset
12
    # cpuset may restrict the number of *available* processors
13
    try:
14
        m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$',
15
                      open('/proc/self/status').read())
16
        if m:
17
            res = bin(int(m.group(1).replace(',', ''), 16)).count('1')
18
            if res > 0:
19
                return res
20
    except IOError:
21
        pass
22
23
    # Python 2.6+
24
    try:
25
        import multiprocessing
26
        return multiprocessing.cpu_count()
27
    except (ImportError, NotImplementedError):
28
        pass
29
30
    # https://github.com/giampaolo/psutil
31
    try:
32
        import psutil
33
        return psutil.cpu_count()   # psutil.NUM_CPUS on old versions
34
    except (ImportError, AttributeError):
35
        pass
36
37
    # POSIX
38
    try:
39
        res = int(os.sysconf('SC_NPROCESSORS_ONLN'))
40
41
        if res > 0:
42
            return res
43
    except (AttributeError, ValueError):
44
        pass
45
46
    # Windows
47
    try:
48
        res = int(os.environ['NUMBER_OF_PROCESSORS'])
49
50
        if res > 0:
51
            return res
52
    except (KeyError, ValueError):
53
        pass
54
55
    # jython
56
    try:
57
        from java.lang import Runtime
58
        runtime = Runtime.getRuntime()
59
        res = runtime.availableProcessors()
60
        if res > 0:
61
            return res
62
    except ImportError:
63
        pass
64
65
    # BSD
66
    try:
67
        sysctl = subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
68
                                  stdout=subprocess.PIPE)
69
        scStdout = sysctl.communicate()[0]
70
        res = int(scStdout)
71
72
        if res > 0:
73
            return res
74
    except (OSError, ValueError):
75
        pass
76
77
    # Linux
78
    try:
79
        res = open('/proc/cpuinfo').read().count('processor\t:')
80
81
        if res > 0:
82
            return res
83
    except IOError:
84
        pass
85
86
    # Solaris
87
    try:
88
        pseudoDevices = os.listdir('/devices/pseudo/')
89
        res = 0
90
        for pd in pseudoDevices:
91
            if re.match(r'^cpuid@[0-9]+$', pd):
92
                res += 1
93
94
        if res > 0:
95
            return res
96
    except OSError:
97
        pass
98
99
    # Other UNIXes (heuristic)
100
    try:
101
        try:
102
            dmesg = open('/var/run/dmesg.boot').read()
103
        except IOError:
104
            dmesgProcess = subprocess.Popen(['dmesg'], stdout=subprocess.PIPE)
105
            dmesg = dmesgProcess.communicate()[0]
106
107
        res = 0
108
        while '\ncpu' + str(res) + ':' in dmesg:
109
            res += 1
110
111
        if res > 0:
112
            return res
113
    except OSError:
114
        pass
115
116
    raise Exception('Can not determine number of CPUs on this system')
117
Comment Below

Report

Would you like to join Ask Sawal!

Why?

  1. Ask Sawal is a fast growing question and answer discussion forum.

  2. 25 lakh+ questions were answered by our Ask Sawal Members.

  3. Each day 1000s of questions asked & 1000s of questions answered.

  4. Ask any question and get answer from 5 Lakh+ Ask Sawal Members.

  5. Constant moderation and reporting option makes questions and answers spam free.

  6. And also, we have free blogging platform. Write an article on any topic.

  7. We have 10000+ visitors each day. So a beneficial platform for link building.

  8. We are allowing link sharing. Create backlinks to your blog site or any site.

  9. Gain extra passive income by sharing your affiliate links in articles and answers.