Skip to main content
 首页 » 编程设计

python之如何调试异步 aiohttp 缓慢

2024年12月31日6sky-heaven

我最近一直在玩 asyncio 模块。下面是我想出的用于发送一些并行请求的代码,这些请求在我的笔记本电脑 (Mac OS) 上似乎运行良好,但在另一台机器 (Ubuntu 18.04) 上似乎运行缓慢。在它运行缓慢的机器(Ubuntu 18.04)中,我安装了 virtualbox vm,其中又安装了 Ubuntu 18.04,令我惊讶的是,代码似乎在那里运行得非常好。我在 Ubuntu 机器上有多个版本的 python,我试图用 3.7.2 运行它。我不确定如何在这里缩小问题范围。如果有人可以帮助我,那就太好了。

我确定这不是网络问题。在 Ubuntu 物理机中,这段代码需要大约 130 秒才能完成。但在 Ubuntu VM 中,它按预期工作,只需不到 5 秒。

import aiohttp 
import asyncio 
import ssl 
import time 
from bs4 import BeautifulSoup 
 
 
async def get_app_updated_date(html_content): 
    soup = BeautifulSoup(html_content, 'lxml') 
    section_titles_divs = [x for x in soup.select('div.hAyfc div.BgcNfc')] 
 
    title_normalization = { 
        'Updated': 'updated', 
    } 
 
    data = { 
        'updated': None, 
    } 
 
    for title_div in section_titles_divs: 
        section_title = title_div.string 
        if section_title in title_normalization: 
            title_key = title_normalization[section_title] 
            value_div = title_div.next_sibling.select_one('span.htlgb') 
            value = value_div.text 
            data[title_key] = value 
    return data 
 
 
async def fetch(session, url, app_id): 
    print(f'Fetching information for {app_id}') 
    async with session.get(url, params={'id': app_id}, ssl=ssl.SSLContext()) as response: 
        html_resp = await response.text() 
        app_lastupdated_date = await get_app_updated_date(html_resp) 
        return {app_id: app_lastupdated_date} 
 
 
async def main(): 
    url = 'https://play.google.com/store/apps/details' 
    app_list = ['com.google.android.youtube', 
                'com.whatsapp', 
                'com.instagram.android', 
                'com.google.android.apps.maps', 
                'com.kiloo.subwaysurf', 
                'com.halfbrick.fruitninjafree', 
                'com.adobe.reader', 
                'org.mozilla.firefox', 
                'com.zeptolab.ctr.ads', 
                'com.fingersoft.hillclimb'] 
    async with aiohttp.ClientSession() as session: 
        url_requests = [fetch(session, url, app_id) for app_id in app_list] 
        print(url_requests) 
        results = await asyncio.gather(*url_requests) 
        for r in results: 
            print(r) 
        print(f'Result size  = {len(results)}') 
 
 
if __name__ == '__main__': 
    start_time = time.time() 
    loop = asyncio.get_event_loop() 
    loop.run_until_complete(main()) 
    print(f'Script execution completed in: {time.time() - start_time} seconds') 

更新: 根据建议,附上我的分析报告。无法理解行话。再次,在此论坛中寻求人们的专业知识。

请您参考如下方法:

我建议您至少缩小到函数范围。使用 profiling IDE 中的模块或分析器(即 Pycharm 提供了非常好的工具)以了解有问题的功能。

但是 IMO,这实际上看起来像是网络问题,因为在裸机上的 Ubuntu 下运行是:

  • python环境
  • 事件循环实现
  • 绑定(bind)到系统包
  • ubuntu 网络(包括 DNS 解析器)

VM 中的 Ubuntu 是:

  • python环境
  • 事件循环实现
  • 绑定(bind)到系统包
  • 从 VM 到主机系统的桥接网络(取决于 VM 设置)
  • windows 网络(包括 DNS 解析器)