PYTHON · 성능
비동기 성능
비동기 프로그래밍의 성능 특성을 이해하고 I/O 바운드 작업을 최적화합니다.
성능고급async비동기성능Semaphore
핵심 설명
비동기 프로그래밍의 성능 특성을 이해하고 I/O 바운드 작업을 최적화합니다.
Python code
import asyncio
import time
async def io_task(name: str, delay: float) -> str:
await asyncio.sleep(delay)
return f"{name} 완료"
async def benchmark_sequential():
start = time.perf_counter()
for i in range(5):
await io_task(f"작업-{i}", 0.5)
return time.perf_counter() - start
async def benchmark_concurrent():
start = time.perf_counter()
await asyncio.gather(
*[io_task(f"작업-{i}", 0.5) for i in range(5)]
)
return time.perf_counter() - start
async def benchmark_batched():
"""배치 처리: 동시성을 제한하며 실행"""
start = time.perf_counter()
sem = asyncio.Semaphore(3)
async def limited(name, delay):
async with sem:
return await io_task(name, delay)
await asyncio.gather(
*[limited(f"작업-{i}", 0.5) for i in range(9)]
)
return time.perf_counter() - start
async def main():
t1 = await benchmark_sequential()
print(f"순차 실행: {t1:.2f}초")
t2 = await benchmark_concurrent()
print(f"동시 실행: {t2:.2f}초 ({t1/t2:.1f}x 빠름)")
t3 = await benchmark_batched()
print(f"배치 실행: {t3:.2f}초 (동시 3개)")
print(f"\n핵심: I/O 대기 시간을 겹치는 것이 비동기의 핵심")
asyncio.run(main())학습 팁
비동기는 I/O 대기 시간을 겹쳐서 총 시간을 줄입니다. CPU 바운드 작업에는 효과가 없습니다.
주의할 점
asyncio.gather()에 수천 개의 태스크를 넣으면 메모리와 연결 수가 폭발합니다. Semaphore로 제한하세요.
자주 묻는 질문
비동기 성능란 무엇인가요?
비동기 프로그래밍의 성능 특성을 이해하고 I/O 바운드 작업을 최적화합니다.
비동기 성능 학습 시 주의할 점은 무엇인가요?
asyncio.gather() 에 수천 개의 태스크를 넣으면 메모리와 연결 수가 폭발합니다. Semaphore 로 제한하세요.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.