Multiprocessing is the primary way to bypass the GIL for CPU-bound tasks.
1from multiprocessing import Pool, cpu_count2import time34def cpu_heavy(n):5 return sum(i * i for i in range(n))67# Compare single vs multi-process8start = time.time()9result = cpu_heavy(10**7)10single = time.time() - start1112start = time.time()13with Pool(cpu_count()) as pool:14 chunk_size = 10**7 // cpu_count()15 chunks = [chunk_size] * cpu_count()16 results = pool.map(cpu_heavy, chunks)17 result = sum(results)18multi = time.time() - start1920print(f"Single: {single:.2f}s, Multi: {multi:.2f}s")
Other approaches:
When multiprocessing is NOT the answer: