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

Spyder中Python多线程处理数据为何出现性能瓶颈?

问题背景
  • 测试目标:修改CSV文件某一列的日期格式,核心目的是验证Python线程功能是否正常,已知存在更简便的日期转换实现方案
  • 运行环境:Spyder + Python 3.8
  • 测试数据规模:10万行CSV记录
  • 测试现象:单进程无线程场景处理耗时约1分30秒;配置80线程时耗时约30秒;线程数提升至200、400时,耗时始终停滞在30秒,没有进一步下降。
代码实现逻辑

整体执行流程如下:

  • 自定义线程类,实现日期格式转换的核心逻辑
  • 根据设定的线程总数,将读取得到的原始DataFrame拆分为对应数量的子DataFrame分片
  • 为每个线程分配一个独立的子DataFrame分片
  • 各线程独立处理自身分片内的日期格式转换任务
  • 所有线程执行完毕后,拼接所有子DataFrame得到最终完整结果

代码中serie为读取CSV得到的原始DataFrame对象,完整代码如下:

import pandas as pd
import numpy as np
import threading
import time

from datetime import datetime
from threading import Thread
from time import process_time

serie=pd.read_csv('XXX.csv')

in_format = "%d/%m/%Y"
out_format = "%Y-%m-%d"

class MonThread (threading.Thread):
    def __init__(self, num_thread):
        threading.Thread.__init__(self)
        self.num_thread = num_thread
    
    # 线程执行函数
    def run(self):
        for self.i in range(dataframes[self.num_thread].index[0], dataframes[self.num_thread].index[0] + dataframes[self.num_thread].shape[0]):
            date_formatee = datetime.strptime(dataframes[self.num_thread].loc[self.i, 'Date'], in_format).strftime(out_format)
            dataframes[self.num_thread].loc[self.i, 'Date'] = date_formatee

nb_thread = 80
dataframes = []

# 按线程数拆分DataFrame
for j in range(nb_thread):
    a = j * (serie.shape[0] // nb_thread)
    if j != nb_thread - 1 :
        b = (j + 1) * (serie.shape[0] // nb_thread)
        df = serie.iloc[a:b,:]
    else: 
        df = serie.iloc[a:,:]
        b = serie.shape[0]
    dataframes.append(df)
    print("Intervalle", j, ": [", a, ",", b, "]")

tps1 = process_time()
print(tps1)

threads = []
for n in range(nb_thread):
    t = MonThread(n)
    t.start()
    threads.append(t)

for t in threads:
    t.join()
    
dataframe_finale = pd.concat(dataframes)

print("\n\n\n")
tps2 = process_time()
print(tps2)
print("temps d'éxécution : ")
print(tps2 - tps1)  
原因说明

耗时无法随线程数增加继续下降不是代码逻辑错误,是Python机制和硬件特性共同导致的:

  • CPython GIL全局解释器锁限制
    常规安装的CPython存在全局解释器锁,同一时刻仅允许一个线程持有GIL执行Python字节码,CPU密集型任务无法通过多线程利用多核实现真正并行。你用到的datetime.strptime属于典型CPU密集操作,多线程下本质是线程交替抢占GIL执行,提速存在天然上限。80线程比单线程快,是因为pandas部分底层操作会临时释放GIL,加上单线程逐行loc赋值本身效率极低,多线程分摊了逐行操作的等待开销,但这个收益不会随线程数上涨无限增加。
  • 线程调度开销的边际效应
    普通消费级CPU的物理核心数大多在4-16之间,线程数超过CPU核心数后,操作系统需要反复在线程间做上下文切换:保存线程执行状态、切换寄存器、刷新CPU缓存,这部分开销会随线程数增长快速升高。你开到200、400线程时,新增的线程调度开销已经完全抵消了多线程带来的收益,自然不会再提速。
  • 代码本身存在固定性能损耗
    你当前用逐行loc赋值的方式修改DataFrame,本身就是pandas中效率极低的操作方式,这部分固定开销不会随线程数增加而减少,也是耗时无法继续下降的原因之一。
补充说明

如果你的目标只是验证线程功能是否正常,现在80线程相对单线程有明确提速,已经证明线程调度、分片处理、结果拼接的逻辑是正常工作的。如果要测试真正的多核并行性能,需要换multiprocessing多进程模块绕过GIL限制,才能看到性能随进程数匹配CPU核心数上升的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 04:39:58