You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python多线程请求为何比串行执行更慢?

问题

我正在学习Python线程相关知识,了解到线程适合处理IO密集型任务。但我编写了一个从API拉取股票价格的简单脚本后,发现多线程代码的运行速度反而比串行代码慢。以下是测试代码及结果:

import requests
import os
from threading import Thread
import time


api_key = os.getenv('ALPHAVANTAGE_API_KEY')
url = 'https://www.alphavantage.co/query?function=OVERVIEW&symbol={}&apikey={}'
symbols = ['AAPL', 'GOOG', 'TSLA', 'MSFT', 'BABA','AAPL', 'GOOG', 'TSLA', 'MSFT', 'BABA','AAPL', 'GOOG', 'TSLA', 'MSFT', 'BABA','AAPL', 'GOOG', 'TSLA', 'MSFT', 'BABA','AAPL', 'GOOG', 'TSLA', 'MSFT', 'BABA','AAPL', 'GOOG', 'TSLA', 'MSFT', 'BABA']
results = []


def get_price(symbol):
    print(f'getting {symbol} price')
    response = requests.get(url.format(symbol, api_key))
    results.append(response.json())


print("Timer started...")
threads = [Thread(target=get_price,args=(symbol,))for symbol in symbols]


if __name__=='__main__':

# run_tasks()
    start = time.time()
    for thread in threads:
        thread.start()

    for thread in threads:
        thread.join()

    # for symbol in symbols:
    #     get_price(symbol)

    end = time.time()
    total_time = end - start
    print("It took {} seconds to make {} API calls".format(total_time, len(symbols)))

多线程代码输出:It took 19.715637922286987 seconds to make 30 API calls
串行代码输出:It took 15.80090594291687 seconds to make 30 API calls

请问有人能解释这一现象的原因吗?

原因解析

出现这种反直觉的结果,核心原因如下:

  • API服务限流
    像Alpha Vantage这类免费API通常会有请求频率限制,当你用多线程一次性发起大量请求时,服务端会识别到高频请求,主动延迟响应甚至临时限制你的访问速度,反而不如串行请求能稳定获取正常响应效率。加上你重复请求了相同的股票代码,服务端可能进一步放慢响应速度。

  • 线程开销抵消优势
    Python线程虽轻量,但创建30个线程的初始化开销、线程间的切换成本不可忽视。如果单个API请求的IO等待时间没有足够覆盖这些开销,多线程的优势就无法体现,甚至拖慢整体速度。

  • 并发数失控导致资源竞争
    一次性启动30个线程同时请求,会导致本地网络栈瞬间处理大量并发连接,引发资源竞争和阻塞,反而不如串行请求能有序利用网络资源。

  • GIL的次要影响
    虽然IO密集型任务会释放GIL,但线程启动、切换时仍会涉及GIL的竞争。如果单个请求的IO等待时间较短,GIL切换的开销会被放大,抵消多线程的优势。

优化建议

  • 限制并发线程数,比如用ThreadPoolExecutor设置5-10个最大工作线程,避免触发API限流。
  • 移除重复的股票代码,减少不必要的API调用。
  • 尝试异步请求框架(如aiohttp),异步模型在IO密集型任务上的开销通常比线程更低。

内容的提问来源于stack exchange,提问作者Musa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 14:45:43