파이썬, 동기식, 비동기식(구형/신형) 함수 사용 비교 예제

 

글. 수알치 오상문

 

import time
import asyncio

# 비동기식 함수 (작업 대상)
async def find_users_async(n):
    for i in range(1, n + 1):
        print(f'{n} times')
        await asyncio.sleep(1)  # 비동기식 지연 함수 
    print(f'{n} 작업 완료')

# 동기식 함수 (작업 대상)
def find_users(n):
    for i in range(1, n + 1):
        print(f'{n} times')
        time.sleep(1)
    print(f'{n} 작업 완료')

#---------------------------------------
    
# 동기식 호출 함수 : 동기식 작업 대상을 호출하는 함수 
def process_sync():
    start = time.time()
    find_users(3)
    find_users(2)
    find_users(1)    
    end = time.time()
    print(f'>>> 동기 처리 총 소요 시간: {end - start}')

# 비동기식 호출 함수 : 비동기 작업 대상을 호출하는 함수 (예전 방식)
async def process_async():
    start = time.time()
    await asyncio.wait([
        find_users_async(3),
        find_users_async(2),
        find_users_async(1),
    ])
    end = time.time()
    print(f'>>> 비동기 처리 총 소요 시간: {end - start}')

# 비동기식 호출 함수 : 비동기 작업 대상을 호출하는 함수 (새 방식)
async def process_async_new():
    start = time.time()
    await asyncio.wait([
        asyncio.create_task(find_users_async(3)),
        asyncio.create_task(find_users_async(2)),
        asyncio.create_task(find_users_async(1)),
    ])
    end = time.time()
    print(f'>>> 비동기 처리 총 소요 시간: {end - start}')

# 테스트 
if __name__ == '__main__':

    process_sync()  # 동기 방식 테스트 
    asyncio.run(process_async())  # 비동기 방식 테스트 (예전)
    asyncio.run(process_async_new())  # 비동기 방식 테스트 (신형)

 

속도 : 비동기(신형) > 비동기(구형) > 동기 

 

[실행 결과] Python 3.10 기준

3 times
3 times
3 times
3 작업 완료
2 times
2 times
2 작업 완료
1 times
1 작업 완료
>>> 동기 처리 총 소요 시간: 6.232004165649414

 

비동기(구형)은 다음과 같은 경고 메시지가 나온다. (파이썬 3.11부터 사용하지 못함)
Warning (from warnings module):
  File "C:/Users/82104/Desktop/python/async_exam.py", line 32
    await asyncio.wait([
DeprecationWarning: The explicit passing of coroutine objects to asyncio.wait() is deprecated since Python 3.8, and scheduled for removal in Python 3.11.
3 times
1 times
2 times
3 times
1 작업 완료
2 times
3 times
2 작업 완료
3 작업 완료
>>> 비동기 처리 총 소요 시간: 3.1708552837371826


3 times
2 times
1 times
3 times
2 times
1 작업 완료
3 times
2 작업 완료
3 작업 완료
>>> 비동기 처리 총 소요 시간: 3.150385618209839


[참고] https://github.com/pythontoday/selenium_python/blob/master/chromedriver/09_selenium_multiprocessing_chrome.py

 

GitHub - pythontoday/selenium_python

Contribute to pythontoday/selenium_python development by creating an account on GitHub.

github.com

 

반응형

+ Recent posts