首页 > 解决方案 > 如何在 Python 3 中使用多处理来提高运行时间

问题描述

我正在开发一个程序,该程序通过空间的一个象限中的一系列方向寻找解决方案,即从 0°(北)到 90°(东)的变化趋势以及从 0° 到 88° 的每个趋势变化. 在每个位置,我希望进行一些计算,其结果取决于三个垂直轴的方向,其中一个轴指向所选位置,另外两个轴也从 0 度旋转到 88 度。为了获得所需的位置,我构建了几个使用矩阵旋转的函数,每个位置都以矩阵形式附加在一个名为“网格”的列表中。之后,我使用多处理在每个位置执行所需的计算,并获得所需的“结果”。

代码看起来像这样:

from numpy import (array, dot)
import multiprocessing
import time

def rotation(times, rotation_matrix, orientation_matrix, grid):
 n = matrix 
 for i in times:
   n = dot(rotation_matrix, n)
   another_function(n, grid) #this is the function that calculates six possible axes positions and appends them in the list grid = 'Grid'
 return

def orient(trend, inclination):
 #this is the function that defines the orientation of the three perpendicular axes in matrix form
 #Some unrelevant calculations here...
 return O_matrix #orientation matrix

def get_solution(grid, input_list):
 #a function to perform complex calculations at each item of the list 'Grid', i.e. at each 
 #orientation in the desired tridimensional space, using an input database list ('Database')
 return solution 

Database = []
Grid = [] #list where all the orientations will be appended
count = range(44) #amount of times I want to perform rotations, used in rotation() function
R_matrix = array(["some array giving the matrix rotation"])
trends = range(0,90) #trends from North to East, excluding 90°
inclinations = range(0,90) #inclinations from 0° to 88°

for i in trends:# this loop creates the orientation grid appended to the list 'Grid'
 for j in inclinations:
  XYZ = orient(i,j)
  rotation(count, R_matrix, XYZ, Grid) 
  
if __name__ == '__main__': #this is only needed if I want to run the script in Windows
 start = time.time()
 p = multiprocessing.Pool()
 results = p.starmap(get_solution, zip(Grid, Database))
 result = list(results)
 end = time.time()

 print('Items in Grid: ', len(Grid))
 print('in ', round(end - start, 2), ' seconds')

我只在三维空间的有限区间内尝试了这段代码,只是为了看看它需要多少时间。为此,我限制了趋势和倾向的范围,得到以下结果:

Items in Grid: 4320
in 182.81 seconds

我正在使用 Python 3.8.10 在 Spyder for Linux 中编译,而这个结果是我在一台 10 年前的 i7 PC 上获得的。在一台装有 Windows、Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz 的较年轻 PC 中,花费了 100 秒以上。考虑到我只搜索我感兴趣的整个空间的一小部分,我觉得这需要太多。任何有助于改进代码以从多处理(或任何其他魔法工具)中获得最佳效果的帮助和建议将不胜感激。

标签: pythonpython-3.xpython-multiprocessing

解决方案


推荐阅读