优化PokeAPI调用性能:快速获取指定HP阈值的前150只宝可梦名称
优化宝可梦HP查询代码的方案
你的代码耗时8.49秒的核心原因是同步串行发起150次API请求,每次请求都要等待网络往返,时间成本被线性放大。以下是几种有效的优化方案:
1. 异步并行请求(最优方案)
用aiohttp替代requests,同时发起所有API请求,总耗时接近单次请求的时间,而非150次的总和。同时直接在请求后过滤数据,避免存储全量冗余数据。
import aiohttp import asyncio async def fetch_pokemon(session, pokemon_id): api_url = f"https://pokeapi.co/api/v2/pokemon/{pokemon_id}" async with session.get(api_url) as response: data = await response.json() return data['name'], data['stats'][0]['base_stat'] async def get_pokemon_with_similar_hp(max_hp): pokemon_names = [] async with aiohttp.ClientSession() as session: # 创建所有请求任务 tasks = [fetch_pokemon(session, i) for i in range(1, 151)] # 并行执行所有任务 results = await asyncio.gather(*tasks) # 过滤符合条件的宝可梦 for name, hp in results: if hp < max_hp: pokemon_names.append(name) return pokemon_names # 同步环境下调用示例(如Flask/Django) # asyncio.run(get_pokemon_with_similar_hp(50))
2. 多线程并行请求(兼容老项目)
如果无法引入异步库,可使用concurrent.futures.ThreadPoolExecutor实现多线程并行请求,同样能大幅缩短耗时。
import requests from concurrent.futures import ThreadPoolExecutor def fetch_pokemon(pokemon_id): api_url = f"https://pokeapi.co/api/v2/pokemon/{pokemon_id}" response = requests.get(api_url) data = response.json() return data['name'], data['stats'][0]['base_stat'] def get_pokemon_with_similar_hp(max_hp): pokemon_names = [] # 控制线程数量,避免请求过多被API限流 with ThreadPoolExecutor(max_workers=20) as executor: results = executor.map(fetch_pokemon, range(1, 151)) for name, hp in results: if hp < max_hp: pokemon_names.append(name) return pokemon_names
3. 缓存数据(长期优化)
如果这个接口会被多次调用,建议将前150只宝可梦的名称和HP数据缓存到本地文件、Redis或数据库中。后续请求直接读取缓存,无需再调用API,耗时可降到毫秒级。
内容的提问来源于stack exchange,提问作者NucyLoodle
相关产品推荐
相关产品推荐

