Asyncio 사용 해보기(2)

code_able·2022년 11월 26일
0

동기 vs 비동기 비교

동기

import time

def test_process1():
    print('테스트 프로세스1 시작')
    print('테스트 프로세스1 5초 대기')
    time.sleep(5)
    print('테스트 프로세스1 종료')

def test_process2():
    print('테스트 프로세스2 시작')
    print('테스트 프로세스2 5초 대기')
    time.sleep(4)
    print('테스트 프로세스2 종료')

if __name__ == "__main__":

    test_process = [test_process1, test_process2]

    start = time.time()
    for i in range(2):
        test_process[i]()
    end = time.time()
    print(f'time taken: {end-start}')
테스트 프로세스1 시작
테스트 프로세스1 5초 대기
테스트 프로세스1 종료
테스트 프로세스2 시작
테스트 프로세스2 5초 대기
테스트 프로세스2 종료
time taken: 9.00633692741394

테스트 프로세스1기 종료되고 테스트 프로세스 2가 실행됩니다.

비동기

import asyncio
import time


async def test_coroutine1():
    print('테스트 코루틴1 시작')
    print('테스트 코루틴1 5초간 대기')
    await asyncio.sleep(5)
    print('테스트 코루틴1 종료')


async def test_coroutine2():
    print('테스트 코루틴2 시작')
    print('테스트 코루틴2 5초간 대기')
    await asyncio.sleep(4)
    print('테스트 코루틴2 종료')


if __name__ == "__main__":
    # 이벤트 루프 정의
    loop = asyncio.get_event_loop()
    start = time.time()
    # # 코루틴이 여러개일 경우 asyncio.gather 사용
    loop.run_until_complete(asyncio.gather(test_coroutine1(), test_coroutine2()))
    end = time.time()

    print(f'time taken: {end-start}')
테스트 코루틴1 시작
테스트 코루틴1 5초간 대기
테스트 코루틴2 시작
테스트 코루틴2 5초간 대기
테스트 코루틴2 종료
테스트 코루틴1 종료
time taken: 5.0033392906188965

테스트 코루틴1이 대기상태 있을 때
테스트 코루틴2가 시작됩니다
동기 방식 보다 약 4초가 절약 되었습니다.

profile
할수 있다! code able

0개의 댓글