PYTHON · 성능
multiprocessing
multiprocessing으로 CPU 바운드 작업을 여러 프로세스에 분산하여 GIL을 우회합니다.
성능중급multiprocessing병렬PoolGIL
핵심 설명
multiprocessing으로 CPU 바운드 작업을 여러 프로세스에 분산하여 GIL을 우회합니다.
Python code
from multiprocessing import Pool, cpu_count
import time
def cpu_intensive(n: int) -> int:
"""CPU 바운드 작업"""
total = 0
for i in range(n):
total += i * i
return total
# 순차 실행
def sequential(tasks):
return [cpu_intensive(n) for n in tasks]
# 병렬 실행
def parallel(tasks, workers=None):
with Pool(workers or cpu_count()) as pool:
return pool.map(cpu_intensive, tasks)
tasks = [500000] * 8
# 벤치마크
start = time.perf_counter()
r1 = sequential(tasks)
t1 = time.perf_counter() - start
print(f"순차: {t1:.3f}초")
start = time.perf_counter()
r2 = parallel(tasks)
t2 = time.perf_counter() - start
print(f"병렬 ({cpu_count()}코어): {t2:.3f}초")
print(f"속도 향상: {t1/t2:.1f}x")
# imap: 지연 평가 (대용량 데이터)
# with Pool() as pool:
# for result in pool.imap_unordered(cpu_intensive, tasks):
# print(f"완료: {result}")
# starmap: 다중 인자
def add(a, b):
return a + b
with Pool() as pool:
results = pool.starmap(add, [(1,2), (3,4), (5,6)])
print(f"starmap 결과: {results}")학습 팁
Pool.imap_unordered()는 결과를 완료 순서대로 반환하여 먼저 끝난 작업부터 처리할 수 있습니다.
주의할 점
프로세스 간 데이터 전달은 pickle 직렬화를 사용하므로 큰 데이터를 전달하면 오히려 느려집니다.
자주 묻는 질문
multiprocessing란 무엇인가요?
multiprocessing 으로 CPU 바운드 작업을 여러 프로세스에 분산하여 GIL을 우회합니다.
multiprocessing 학습 시 주의할 점은 무엇인가요?
프로세스 간 데이터 전달은 pickle 직렬화를 사용하므로 큰 데이터를 전달하면 오히려 느려집니다.