From 44feda3cd0454cd00028e09f3151de67e8aad76f Mon Sep 17 00:00:00 2001 From: Charles-Francois Natali Date: Mon, 20 May 2013 14:40:46 +0200 Subject: Issue #17914: Add os.cpu_count(). Patch by Yogesh Chaudhari, based on an initial patch by Trent Nelson. --- Lib/multiprocessing/__init__.py | 25 +++---------------------- Lib/test/test_os.py | 10 ++++++++++ 2 files changed, 13 insertions(+), 22 deletions(-) (limited to 'Lib') diff --git a/Lib/multiprocessing/__init__.py b/Lib/multiprocessing/__init__.py index b5f16d78f4..b42613f8c2 100644 --- a/Lib/multiprocessing/__init__.py +++ b/Lib/multiprocessing/__init__.py @@ -85,30 +85,11 @@ def cpu_count(): ''' Returns the number of CPUs in the system ''' - if sys.platform == 'win32': - try: - num = int(os.environ['NUMBER_OF_PROCESSORS']) - except (ValueError, KeyError): - num = 0 - elif 'bsd' in sys.platform or sys.platform == 'darwin': - comm = '/sbin/sysctl -n hw.ncpu' - if sys.platform == 'darwin': - comm = '/usr' + comm - try: - with os.popen(comm) as p: - num = int(p.read()) - except ValueError: - num = 0 + num = os.cpu_count() + if num is None: + raise NotImplementedError('cannot determine number of cpus') else: - try: - num = os.sysconf('SC_NPROCESSORS_ONLN') - except (ValueError, OSError, AttributeError): - num = 0 - - if num >= 1: return num - else: - raise NotImplementedError('cannot determine number of cpus') def freeze_support(): ''' diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py index 3a38285b57..65d3c3bf6e 100644 --- a/Lib/test/test_os.py +++ b/Lib/test/test_os.py @@ -2216,6 +2216,15 @@ class OSErrorTests(unittest.TestCase): else: self.fail("No exception thrown by {}".format(func)) +class CPUCountTests(unittest.TestCase): + def test_cpu_count(self): + cpus = os.cpu_count() + if cpus is not None: + self.assertIsInstance(cpus, int) + self.assertGreater(cpus, 0) + else: + self.skipTest("Could not determine the number of CPUs") + @support.reap_threads def test_main(): support.run_unittest( @@ -2246,6 +2255,7 @@ def test_main(): TermsizeTests, OSErrorTests, RemoveDirsTests, + CPUCountTests, ) if __name__ == "__main__": -- cgit v1.2.1