在MPI上合并排序

时间:2019-01-07 19:49:56

标签: python mpi

我想在MPI中编写合并排序。一开始,我将阵列等分,然后在一个处理器上发送一部分。所有处理器都对自己的数组进行排序。最后,我合并数组。

globalArraySize = 1000000
globalArray = []
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()

heigth = math.log(size,2)
localArraySize = globalArraySize/size
localArray = np.empty(localArraySize,dtype=np.int)


if rank == 0:
    globalArray = [0] * globalArraySize
    for index,val in enumerate(globalArray):
        globalArray[index] = randint(0,globalArraySize)

    localArray = globalArray[0:localArraySize]

    for i in range(1,size):
        comm.send(globalArray[i*localArraySize:((i+1)*localArraySize)],dest=i,tag=13)
else:
    localArray = comm.recv(source=0,tag=13)

start_time = time.time()
if rank == 0:
    globalArray = mergeSort(heigth,rank,localArray,comm,globalArray)
else:
    mergeSort(heigth,rank,localArray,comm,None)
end = time.time() - start_time


if rank == 0:
    # print(globalArray)
    print('time: ',end)

这里为每个处理器提供功能

def mergeSort(heigth,id, localArray,comm,globalArray):
    parent = 0
    rightChild = 0
    myHeight = 0
    half1 = []
    half2 = []
    mergeResult = []
    localArray = np.sort(localArray,kind="mergesort")
    half1 = localArray
    while myHeight < heigth:
        parent = (id & (~(1 << myHeight)))
        if parent == id:
            rightChild = (id | (1 << myHeight))
            half2 = comm.recv(source=rightChild,tag=14)


            mergeResult = merge(half1,half2)
            half1 = mergeResult
            mergeResult = None
            myHeight +=1
        else:
            comm.send(half1,dest = parent,tag = 14)
            myHeight = heigth
    if id == 0:
        globalArray = half1

    return globalArray


def merge(firstHalf,secondHalf):
    array = [None] * (len(firstHalf)+len(secondHalf))
    i = 0
    j = 0
    k = 0
    while i <len(firstHalf) and j < len(secondHalf):
        if firstHalf[i] < secondHalf[j]:
            array[k] = firstHalf[i]
            i += 1
        else:
            array[k] = secondHalf[j]
            j += 1
        k += 1
    while i < len(firstHalf):
        array[k] = firstHalf[i]
        i += 1
        k += 1
    while j < len(secondHalf):
        array[k] = secondHalf[j]
        j += 1
        k += 1
    return array

我的代码在两个处理器上的运行速度比在一个处理器上的运行速度慢。我不知道该如何更改。有人有主意吗?

0 个答案:

没有答案