파이썬, 동기식, 비동기식(구형/신형) 함수 사용 비교 예제
글. 수알치 오상문
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
GitHub - pythontoday/selenium_python
Contribute to pythontoday/selenium_python development by creating an account on GitHub.
github.com
'Python 기초' 카테고리의 다른 글
AttributeError: module 'collections' has no attribute 'Callable' (0) | 2022.07.30 |
---|---|
파이썬, 동기식, 비동기식(구형/신형) 함수 사용 비교 예제 2 (0) | 2022.07.30 |
파이썬, 멀티 스레딩 (0) | 2022.07.28 |
오늘 또는 기준 일자의 이전, 이후 상대 날짜 함수 예제 (0) | 2022.07.14 |
파이썬, 회사명에서 주식회사 표현 및 공백 제거 (정규식 아님) (0) | 2022.07.08 |