Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/parallel/ncpus.py
4049 views
1
"""
2
CPU Detection
3
"""
4
# Parallel Python Software: http://www.parallelpython.com
5
# Copyright (c) 2005-2008, Vitalii Vanovschi
6
# All rights reserved.
7
# Redistribution and use in source and binary forms, with or without
8
# modification, are permitted provided that the following conditions are met:
9
# * Redistributions of source code must retain the above copyright notice,
10
# this list of conditions and the following disclaimer.
11
# * Redistributions in binary form must reproduce the above copyright
12
# notice, this list of conditions and the following disclaimer in the
13
# documentation and/or other materials provided with the distribution.
14
# * Neither the name of the author nor the names of its contributors
15
# may be used to endorse or promote products derived from this software
16
# without specific prior written permission.
17
#
18
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
28
# THE POSSIBILITY OF SUCH DAMAGE.
29
30
######
31
# This is from ParallelPython (the pp.py file).
32
33
import os, subprocess
34
35
def ncpus():
36
"""
37
Detects the number of effective CPUs in the system.
38
39
EXAMPLES::
40
41
sage: sage.parallel.ncpus.ncpus() # random output -- depends on machine.
42
2
43
"""
44
#for Linux, Unix and MacOS
45
if hasattr(os, "sysconf"):
46
if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
47
#Linux and Unix
48
ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
49
if isinstance(ncpus, int) and ncpus > 0:
50
return ncpus
51
else:
52
#MacOS X
53
#deprecated: return int(os.popen2("sysctl -n hw.ncpu")[1].read())
54
process = subprocess.Popen("sysctl -n hw.ncpu", shell=True, stdin=subprocess.PIPE, stdout = subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
55
return int(process.stdout.read())
56
#for Windows
57
if os.environ.has_key("NUMBER_OF_PROCESSORS"):
58
ncpus = int(os.environ["NUMBER_OF_PROCESSORS"])
59
if ncpus > 0:
60
return ncpus
61
#return the default value
62
return 1
63
64