美文网首页
Python tornado aoihttp性能对比

Python tornado aoihttp性能对比

作者: 梨花菜 | 来源:发表于2021-03-31 16:21 被阅读0次

tornado

    def get_api_info(self):
        """
        获取yapi的所有api的详细信息
        """

        api_info = []
        token = self.__token

        start = time.time()
        i = 0
        url = self.__yapi_base_url + '/api/interface/get'
        api_info = []

        def handle_request(response):
            res = json.loads(response.body, encoding='utf-8')
            api_info.append(res['data'])
            nonlocal i
            i -= 1
            if i <= 0:
                ioloop.IOLoop.instance().stop()

        http_client = httpclient.AsyncHTTPClient()
        for api_id in self.api_ids:
            i += 1
            http_client.fetch(f'{url}?token={token}&id={api_id}', handle_request, method='GET')
        ioloop.IOLoop.instance().start()
        self.api_info = api_info
        logger.info(f"end: {time.time() - start}")

679个http请求,耗时9.85s

aoihttp

    def get_api_info(self):
        """
        获取yapi的所有api的详细信息
        """

        api_info = []
        token = self.__token


        url = self.__yapi_base_url + '/api/interface/get'
        api_info = []

        async def get_results(api_id):
            # 异步发送请求
            async with aiohttp.ClientSession() as session:
                async with session.get(f'{url}?token={token}&id={api_id}', timeout=30) as response:
                    assert response.status == 200
                    res = await response.read()
                    api_info.append(json.loads(res, encoding='utf-8'))

        start = time.time()
        tasks = [get_results(api_id) for api_id in self.api_ids]
        loop = asyncio.get_event_loop()
        loop.run_until_complete(asyncio.wait(tasks))
        loop.close()
        self.api_info = api_info
        logger.info(f"end: {time.time() - start}")

679个http请求,耗时10.08s

相关文章

网友评论

      本文标题:Python tornado aoihttp性能对比

      本文链接:https://www.haomeiwen.com/subject/myqahltx.html