Created
October 12, 2024 18:06
-
-
Save ammar-faifi/a06e8b50cb3b237491722d424836922a to your computer and use it in GitHub Desktop.
Bench mark Python 3.13 w/ and w/o GIL enabled.
This file contains hidden or 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
import time | |
import multiprocessing | |
import threading | |
from concurrent.futures import ThreadPoolExecutor | |
def cpu_bound_task(n): | |
"""A CPU-bound task that calculates the sum of squares.""" | |
return sum(i * i for i in range(n)) | |
def run_sequential(numbers): | |
"""Run the task sequentially.""" | |
return [cpu_bound_task(num) for num in numbers] | |
def run_multiprocessing(numbers): | |
"""Run the task using multiprocessing.""" | |
with multiprocessing.Pool() as pool: | |
return pool.map(cpu_bound_task, numbers) | |
def run_threading(numbers): | |
"""Run the task using threading.""" | |
with ThreadPoolExecutor() as executor: | |
return list(executor.map(cpu_bound_task, numbers)) | |
if __name__ == "__main__": | |
# Input: list of numbers to process | |
numbers = [10_000_000 + x for x in range(20)] | |
# Sequential approach | |
start_time = time.perf_counter() | |
sequential_result = run_sequential(numbers) | |
sequential_time = time.perf_counter() - start_time | |
# Multiprocessing approach | |
start_time = time.perf_counter() | |
multiprocessing_result = run_multiprocessing(numbers) | |
multiprocessing_time = time.perf_counter() - start_time | |
# Threading approach | |
start_time = time.perf_counter() | |
threading_result = run_threading(numbers) | |
threading_time = time.perf_counter() - start_time | |
# Print results | |
print(f"Sequential time: {sequential_time:.2f} seconds") | |
print(f"Threading time: {threading_time:.2f} seconds") | |
print(f"Multiprocessing time: {multiprocessing_time:.2f} seconds") | |
print(f"Threading speedup: {sequential_time / threading_time:.2f}x") | |
print(f"Multiprocessing speedup: {sequential_time / multiprocessing_time:.2f}x") | |
# Verify results are the same | |
assert ( | |
sequential_result == multiprocessing_result == threading_result | |
), "Results do not match!" | |
print("Results verified: all approaches produce the same output.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's my result using
Python 3.13.0rc3
vsPython 3.13.0rc3t