PC与Mac间含for循环的Python函数执行时间量级差异
Pandas循环函数在Windows与Mac上的巨大性能差异排查
原始场景性能差异
我在Windows系统的Jupyter Notebook中运行一个包含多层for循环的函数,处理shape为(68000,10)的DataFrame。设备配置为11代Intel i7-1165G7 2.8GHz处理器(使用1.5年)、16GB内存,函数执行耗时2928秒,cProfile结果显示nt.stat方法耗时812秒。
同事使用4年旧款Mac运行同一函数仅耗时191秒,且其cProfile结果中无nt.stat项。另一旧款Windows设备运行耗时更长。
复现测试情况
为排查问题,我制作了可复现示例代码:
import numpy as np import pandas as pd import cProfile df_shape = [100000, 8] df = pd.DataFrame(np.random.uniform(0, 0.3, df_shape), index = pd.date_range('2022-01-01', periods=df_shape[0], freq='H')) df.columns = ['loss_' + str(i) for i in range(df_shape[1])] var_incoming = np.random.normal(550, 80, df.shape[0]) def test_func(df_, vars): a_dct = {} wf_dct = {} res_lst = [] wf_res_lst = [] for i in range(df_.shape[0]): y = vars[i] for j, z in df_.iloc[i, :].items(): a = z * y a_dct[j] = a y = y * (1 - z) wf_dct[j] = y temp1 = pd.DataFrame(dict(a_dct), index=[df_.index[i]]) temp2 = pd.DataFrame(dict(wf_dct), index=[df_.index[i]]) res_lst.append(temp1) wf_res_lst.append(temp2) res = pd.concat(res_lst, axis=0) wf = pd.concat(wf_res_lst, axis=0) return res, wf
运行这段复现代码后,两台设备的执行时间差异明显缩小,且nt.stat项不再出现在cProfile结果中。Windows设备与Mac设备的cProfile结果截图分别为:
- Windows执行结果截图
- Mac执行结果截图
疑问
为何原始场景中会出现如此悬殊的执行时间差异?
内容的提问来源于stack exchange,提问作者matsuo_basho
相关产品推荐
相关产品推荐

