Python에서 비동기 및 병렬 처리를 최적화하기 위해 사용되는 여러 라이브러리 및 메커니즘은 I/O 작업이나 CPU 작업의 병렬화를 통해 코드 실행 속도를 높일 수 있다.
async def async_func():
await asyncio.sleep(1)
return "비동기 작업 완료"
async def main():
result = await async_func()
print(result)
asyncio.run(main())
: 이 코드는 1초동안 비동기적으로 대기한 후 작업을 완료한다.
import asyncio
async def async_func():
await asyncio.sleep(1)
return "비동기 작업 완료"
async def main():
results = await asyncio.gather(async_func(), async_func())
print(results)
asyncio.run(main())
: async_func을 동시에 두번 호출하여, 각 작업이 완료될 때까지 기다린다.
import concurrent.futures
def sync_task(seconds):
time.sleep(seconds)
return f"{seconds}초 후 작업 완료"
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = [executor.submit(sync_task, sec) for sec in [1, 2, 3]]
results = [f.result() for f in concurrent.futures.as_completed(futures)]
print(results)
: 1초, 2초, 3초 동안 대기하는 작업을 동시에 실행하고 결과를 반환
import asyncio
import concurrent.futures
def sync_task(seconds):
time.sleep(seconds)
return f"{seconds}초 후 작업 완료"
async def async_main():
with concurrent.futures.ThreadPoolExecutor() as executor:
loop = asyncio.get_event_loop()
tasks = [loop.run_in_executor(executor, sync_task, sec) for sec in [1,2,3]]
result = await asyncio.gather(*tasks)
print(results)
asyncio.run(async_main())
: 이 코드는 비동기 작업과 스레드 풀을 함께 사용하여 동시적으로 실행된다.
import asyncio, time
def blocking_task():
time.sleep(2)
return "블로킹작업 완료"
async def main():
result = await asyncio.to_thread(blocking_task)
print(result)
asyncio.run(main()) : 이 코드는 blocking_task를 비동기적으로 호출하여 블로킹 없이 2초 대기 후 작업을 완료한다.import asyncio
async def async_task():
await asyncio.sleep(1)
pirnt("비동기 작업 완료:)
loop = asyncio.get_event_loop()
loop.run_until_complete(async_task()) : 이코드는 이벤트 루프에서 비동기 작업을 실행하는 방법을 보여준다.run_in_executor
: 기존 동기함수를 비동기적으로 실행할 수 있도록 함.
: 이는 ThreadPoolExecutor와 함께 사용가능하며, CPU-bound 작업을 비동기 환경에서 실행하는데 유용하다.
import asyncio
import time
def blocking_task(seconds):
time.sleep(seconds)
return f"{seconds}초 후 작업 완료"
async def main():
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(None, blocking_task, 2)
print(result)
asyncio.run(main())
: 블로킹 작업을 비동기적으로 처리하면서도, 비동기 함수에서 동기 작업을 실행하는 코드
import asyncio
async def task():
await asyncio.sleep(1)
return "작업1완료"
async def task2():
await asyncio.sleep(2)
return "작업2완료"
async def main():
results = await asyncio.gather(task1(), task2())
print(results)
asyncio.run(main()) : 두개의 작업을 동시에 실행하고 작업이 모두 완료될때까지 기다리는 코드
멋있네요 잘봤어요