Skip to main content
 首页 » 编程设计

python之在 Python 中并行化代码

2024年10月17日8mfryf

我正在使用一个名为 Abaqus 的商业分析软件,它有一个 Python 接口(interface)来读取输出值。

我刚刚在下面给出了示例代码(未运行):

myOdb 包含我从中提取数据的所有信息。需要注意的是,我无法使用 2 个单独的程序打开文件。

下面显示的代码 1 和代码 2 彼此独立工作,它们只需要 myOdb。

有没有办法在我读取 odb 后将代码 1 和 2 并行化?

# Open the odb file  
myOdb = session.openOdb(name=odbPath) 
 
# Code 1 
for i in range(1, NoofSteps+1): 
    frames = myOdb.steps[stepName].frames  
    lastframe=frames[-1]    
    RFD = lastframe.fieldOutputs['RF']  
 
    sum1=0 
 
    for value in RFD.values: 
        sum1=sum1+value.data[1]    
 
# Code 2 
for i in range(1, NoofSteps+1): 
    frames = myOdb.steps[stepName].frames  
    lastframe=frames[-1]    
 
    for j in range(4,13): 
        file2=open('Fp'+str(j)+stepName,'w') 
        b=lastframe.fieldOutputs[var+str(j)] 
        fieldValues=b.values 
        for v in fieldValues: 
            file2.write('%d %6.15f\n' % (v.elementLabel, v.data)) 

请您参考如下方法:

如果您要做的只是达到基本的多处理水平,这就是您所需要的:

import multiprocessing 
 
#Push the logic of code 1 and code 2 into 2 functions. Pass whatever you need 
#these functions to access as arguments. 
 
def code_1(odb_object, NoofSteps): 
   for i in range(1, NoofSteps+1): 
    frames = odb_object.steps[stepName].frames  
    #stepName? Where did this variable come from? Is it "i"? 
    lastframe=frames[-1]    
    RFD = lastframe.fieldOutputs['RF']  
 
    sum1=0 
 
    for value in RFD.values: 
        sum1=sum1+value.data[1] 
 
def code_2(odb_object, NoofSteps): 
    for i in range(1, NoofSteps+1): 
        frames = odb_object.steps[stepName].frames  
        #stepName? Where did this variable come from? Is it "i"? 
        lastframe=frames[-1]    
 
        for j in range(4,13): 
            file2=open('Fp'+str(j)+stepName,'w') 
            b=lastframe.fieldOutputs[var+str(j)] 
            fieldValues=b.values 
            for v in fieldValues: 
                file2.write('%d %6.15f\n' % (v.elementLabel, v.data)) 
 
if __name__ == "__main__": 
    # Open the odb file  
    myOdb = session.openOdb(name=odbPath) 
    #Create process objects that lead to those functions and pass the 
    #object as an argument. 
    p1 = multiprocessing.Process(target=code_1, args=(myOdb,NoofSteps, ))  
    p2 = multiprocessing.Process(target=code_2, args=(myOdb,NoofSteps,))  
    #start both jobs 
    p1.start() 
    p2.start() 
    #Wait for each to finish. 
    p1.join() 
    p2.join() 
    #Done 

将代码的“主要”部分隔离到一个主 block 中,就像我上面显示的那样,不要,我的意思是绝对不要使用全局变量。确保您正在使用的所有变量在每个函数的命名空间中都可用。

我建议学习更多关于 Python 和 GIL 问题的知识。阅读有关多处理模块的信息 here .