有人可以帮我并行处理 Python 吗?

Can someone help me with parallel processing for Python?

我正在寻找一种可能的解决方案来并行读取和触发数据(在我的例子中是波形数据)。

我有一个列表 (wfpathlist),只是一个包含具有给定文件路径的字符串的列表:

for fn in wfpathlist:
    st = readWaveform(fn, bpfreq=[5.,30.])
    coinc = CoincidenceTimes(st)
    triggerlist += coinc.getCoincTimes()
    events += cutWithList(wfpath=fn, trigg=coinc.getCoincTimes(), 
    station=self.getStation())

readWaveform 只是一个读取和过滤数据的简短函数:

def readWaveform(wfpath, bpfreq=[5., 30.]):
    st = read(wfpath)
    st.filter('bandpass', freqmin=bpfreq[0], freqmax=bpfreq[1])
    return st

对于只对编程有非常基本了解的人来说,是否有一个简单的解决方案来让这个 for 循环 运行 并行?

非常感谢,

丹尼斯

您可以在函数中实现 for 循环,并使用 multiprocessing.Pool() 对象调用该函数。 这将使循环的执行并行化,并且应该会增加一个很好的加速。

示例:

from multiprocessing import Pool

def func(fn): 
    st = readWaveform(fn, bpfreq=[5.,30.])
    coinc = CoincidenceTimes(st)
    triggerlist += coinc.getCoincTimes()
    events += cutWithList(wfpath=fn, trigg=coinc.getCoincTimes(), 
    station=self.getStation())

if __name__ == '__main__':
    p = Pool(4) # if you have 4 cores in your processor
    p.map(func, wfpathlist)

来源:https://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers

请注意,某些 python 实现的函数已经使用多处理(在 numpy 中很常见),因此在执行此解决方案之前,当您的脚本 运行 时,您应该检查您的处理器 activity。

编辑:糟糕,您应该直接将您的列表发送到池中。我更正了代码。