Last active
March 9, 2024 17:25
-
-
Save rubenhortas/a5b8650d1668cbafe8d2df90afe401c8 to your computer and use it in GitHub Desktop.
Python program to put the CPU at 100% usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A good example of a Python program that can put the CPU at 100% usage involves creating a CPU-intensive task | |
and then distributing this task across all CPU cores using the multiprocessing module. | |
""" | |
import math | |
import multiprocessing | |
from concurrent.futures import ProcessPoolExecutor | |
def _intensive_task(n: int) -> int: | |
# CPU-intensive task | |
return sum([math.sqrt(i) for i in range(1, n)]) | |
if __name__ == '__main__': | |
print('Starting task...') | |
with ProcessPoolExecutor(multiprocessing.cpu_count()) as exe: | |
results = list(exe.map(_intensive_task, range(1, 50000))) # distributing this task across all CPU cores | |
print('Done.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment