47
My script is CPU-bound and slow. How can I use multiple cores?
Loading...
Q&A · Answered
My script is CPU-bound and slow. How can I use multiple cores?
Accepted answer
from multiprocessing import Pool, cpu_count
def process_item(item):
# CPU-intensive task
return item * item
# Using Pool
items = list(range(1000))
with Pool(processes=cpu_count()) as pool:
results = pool.map(process_item, items)
# For more control
from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor(max_workers=4) as executor:
results = list(executor.map(process_item, items))Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.