티스토리 뷰

asyncio 와 asiohttp 에 대한 자세한 내용은 구글을 검색을 통해 얻을 수 있습니다.

single thread 를 활용한 비동기 프로그래밍 이라고 생각하시면 될 것 같습니다.

I/O Bound 와 CPU Bound 라는 개념 또한 나오는데 Synchronous(동기) 방식을 사용하면 I/O Bound 성능에 따라서

프로그램의 속도에 아주 큰 영향을 미치게 됩니다.

(asyncio 에 대해서 추후 정리하도록 하겠습니다.)

 

동기 방식을 이용하여 간단히 네이버 금융을 통해서 삼성전자의 주식을 50페이지 정도 조회하게 되면 

1.797 s 의 시간이 소요 됩니다.

import requests
import time


url = 'https://finance.naver.com/item/sise_day.nhn?code={code}&page={page}'


def sync_fetch():
    res = [requests.get(url.format(code='005930', page=i))
           for i in range(1, 50)]
    return res


if __name__ == '__main__':

    start = time.time()
    sync_fetch()
    end = time.time()
    print(f"elapsed time = {end - start}s")

elapsed time = 1.797

 

비동기 프로그래밍을 통해 똑같은 방식으로 대략 14배 이상이 빨리지는 성능을 얻을 수 있습니다.

import aiohttp
import asyncio
import time


async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()


async def main():
    async with aiohttp.ClientSession() as session:

        url = 'https://finance.naver.com/item/sise_day.nhn?code={code}&page={page}'
        futures = [asyncio.ensure_future(fetch(session, url.format(code='005930', page=i)))
                   for i in range(1, 50)]
        res = await asyncio.gather(*futures)
        return res

if __name__ == '__main__':

    loop = asyncio.get_event_loop()
    start = time.time()
    result = loop.run_until_complete(main())
    end = time.time()
    print(f"elapsed time = {end - start}s")
    loop.close()

elapsed time = 0.124

 

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함