w3resource

Python: Check number of CPUs

Python Basic: Exercise-47 with Solution

Write a Python program to find out the number of CPUs used.

Sample Solution-1:

Python Code:

import multiprocessing
print(multiprocessing.cpu_count())

Sample Output:

4 

Explanation:

multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows.

cpu_count() function returns the number of CPUs in the system.

The above Python code imports the multiprocessing module and then calls its cpu_count() function to get the number of CPU cores on the current system. The code then calls print() function to print the number of CPU cores on the system to the console output.

Flowchart:

Flowchart: Find out the number of CPUs using.

Sample Solution-2:

Python Code:

import os
print(os.cpu_count())

Sample Output:

2

Explanation:

The 'OS' module provides a portable way of using operating system dependent functionality. cpu_count() function returns the number of CPUs in the system. Returns None if undetermined.

The above Python code imports the multiprocessing module and then calls its cpu_count() function to get the number of CPU cores on the current system.

When the cpu_count() function is called, it returns the number of CPU cores on the system. The code then calls print() function to output the number of CPU cores on the system to the console output.

Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a python program to get the path and name of the file that is currently executing.
Next: Write a Python program to parse a string to Float or Integer.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Joining Collection:

name = ["Owen", "Eddie"] 
print(" ".join(name))
Owen Eddie

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook