Python线程执行时间不一致

时间:2018-08-24 15:51:50

标签: python python-3.x multithreading

  • 使用threading库来加速计算点云中每个点的邻域。通过在帖子底部调用函数CalculateAllPointsNeighbors
    该函数接收搜索半径,最大邻居数和用于拆分工作的线程数。在任何一点上都没有改变。每个点都将数据存储在自己的np.ndarray单元中,该单元由其自己的索引访问。

  • 以下函数乘以N个线程数才能完成所有点邻域计算所需的时间:

    def TimeFuncThreads(classObj, uptothreads):
        listTimers = []
    
        startNum = 1
        EndNum = uptothreads + 1
    
        for i in range(startNum, EndNum):
            print("Current Number of Threads to Test: ", i)
            tempT = time.time()
            classObj.CalculateAllPointsNeighbors(searchRadius=0.05, maxNN=25, maxThreads=i)
            tempT = time.time() - tempT
            listTimers.append(tempT)
    
        PlotXY(np.arange(startNum, EndNum), listTimers)
    
    • 问题是,每次运行我得到的结果都非常不同。这是来自函数TimeFuncThreads的5次后续运行的图。 X轴是线程数,Y是运行时。 Graphs首先,它们看起来完全是随机的。其次,没有明显的加速提升。

我现在很困惑我是否错误地使用了threading库,这是我得到的这种行为吗?


  • 处理线程的函数和正在从每个线程调用的函数:

    def CalculateAllPointsNeighbors(self,searchRadius = 0.20,maxNN = 50,maxThreads = 8):

        threadsList = []
        pointsIndices = np.arange(self.numberOfPoints)
        splitIndices = np.array_split(pointsIndices, maxThreads)
    
        for i in range(maxThreads):
            threadsList.append(threading.Thread(target=self.GetPointsNeighborsByID,
                                                args=(splitIndices[i], searchRadius, maxNN)))
    
        [t.start() for t in threadsList]
        [t.join() for t in threadsList]
    
    
    
    def GetPointsNeighborsByID(self, idx, searchRadius=0.05, maxNN=20):
        if isinstance(idx, int):
            idx = [idx]
    
        for currentPointIndex in idx:
            currentPoint = self.pointsOpen3D.points[currentPointIndex]
            pointNeighborhoodObject = self.GetPointNeighborsByCoordinates(currentPoint, searchRadius, maxNN)
            self.pointsNeighborsArray[currentPointIndex] = pointNeighborhoodObject
            self.__RotatePointNeighborhood(currentPointIndex)
    

1 个答案:

答案 0 :(得分:0)

很高兴成为向您介绍Python Gil的人。这是一个非常好的功能,它使使用Python中的线程进行并行处理成为噩梦。

如果您确实想提高代码速度,则应查看the multiprocessing module