什麼是MPI
MPI(Message Passing Interface)是目前最重要的一個基於消息傳遞的並行編程工具,它具有移植性好、功能強大、效率高等許多優點,而且有多種不同的免費、高效、實用的實現版本,幾乎所有的並行計算機廠商都提供對它的支持,成爲了事實上的並行編程標準。
MPI是一個庫,而不是一門語言,因此對MPI的使用必須和特定的語言結合起來進行。MPI不是一個獨立的自包含系統,而是建立在本地並行程序設計環境之上,其進程管理和I/O均由本地並行程序設計環境提供。例如,MPI可以建立在IBM SP2的POE/MPL之上,也可以建立在Intel Paragon的OSF/NX。除了這些商業版本的MPI實現,還有一些免費版的MPI實現,主要有MPICH,LAM和CHIMP。
Linux下MPI環境的搭建
在Linux環境下搭建MPI環境:
sudo apt-get install mpich
編寫C語言或C++代碼時,在頭文件中包含include "mpi.h"
便可以在代碼中使用mpi的並行語句了。
C語言編譯mpi程序:mpicc example.c -o example
C++編譯mpi程序:mpic++ example.c -o example
運行mpi程序:mpiexec -n 4 ./example
(4爲指定運行的進程數)
利用MPI計算π值
根據積分法易得,求π值的串行代碼如下:
int n = 100, x,sum;
int h = 1.0/n;
for(int i=1; i<=n; i++)
{
x= (i - 0.5)/n;
sun += 4.0/(1+x*x);
}
pi = sum*h;
printf("pi = %d\n",pi);
不難改成mpi並行代碼:
//*計算π的C語言 MPI編程代碼段*//
#include "mpi.h"
#include <stdio.h>
#include <math.h>
double f(double);
double f(double a)
{
return (4.0/(1.0 + a*a));
}
int main(int argc, char *argv[])
{
int done = 0, n, myid, numprocs, i;
double PI25DT = 3.141592653589793238462643;
double mypi, pi, h, sum, x;
double startwtime = 0.0, endwtime;
int namelen;
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argc, &argv); //mpi的初始化
MPI_Comm_size(MPI_COMM_WORLD, &numprocs); //獲取線程數
MPI_Comm_rank(MPI_COMM_WORLD, &myid); //獲取線程id值
MPI_Get_processor_name(processor_name, &namelen); //獲取處理器名稱
fprintf(stderr, "Process %d on %s\n", myid, processor_name);
n = 0;
while(!done)
{
if(myid == 0)
{
/* printf("Enter the number of intervals: (0 quits)");
scanf("%d",&n); */
if(n == 0)
n = 100;
else
n = 0;
startwtime = MPI_Wtime();
}
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD); //進行廣播傳送消息
if(n == 0)
done = 1;
else
{
h = 1.0/(double)n;
sum = 0.0;
for(i=myid+1; i<=n; i+=numprocs) //各線程計算自己的面積
{
x = h * ((double)i - 0.5);
sum += f(x);
}
mypi = h * sum;
MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); //歸約,mypi爲發送方,pi爲接收方
if(myid == 0)
{
printf("pi is approximately %.16f,Error is %.16f\n",pi, fabs(pi-PI25DT));
endwtime = MPI_Wtime();
printf("wall clock time = %f\n", endwtime-startwtime);
}
}
}
MPI_Finalize(); //mpi結束
return 0;
}
利用MPI進行PSRS並行排序
PSRS的排序算法思想如下:
n個元素A[1..n]分成p組,每組A[(i-1)n/p+1..in/p],i=1~p
(1)均勻劃分:將n個元素A[1..n]均勻劃分成p段,每個pi處理
A[(i-1)n/p+1..in/p]
(2)局部排序:pi調用串行排序算法對A[(i-1)n/p+1..in/p]排序
(3)選取樣本:pi從其有序子序列A[(i-1)n/p+1..in/p]中選取p個樣本元素
(4)樣本排序:用一臺處理器對p2個樣本元素進行串行排序
(5)選擇主元:用一臺處理器從排好序的樣本序列中選取p-1個主元,並
播送給其他pi
(6)主元劃分:pi按主元將有序段A[(i-1)n/p+1..in/p]劃分成p段
(7)全局交換:各處理器將其有序段按段號交換到對應的處理器中
(8)歸併排序:各處理器對接收到的元素進行歸併排序
mpi編程思路如下:
1.獲取整個數組的起始位置和子數組大小;
2.調用MPI_Barrier(MPI_COMM_WORLD)進行同步;
3.調用階段一函數,對子數組進行局部排序,以及正則採樣;
4.調用階段二函數,對正則採樣的樣本進行排序,選擇主元和主元劃分;
5.調用階段三函數,進行全局對全局的發送,並且計算劃分的總大小,給新劃分分配空間;
6.調用階段四函數,將全局交換後的數據進行歸併排序,併發送各排序好的子列表回根進程;
7.打印輸出排好序的數組。
代碼如下:
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <assert.h>
#include <sys/time.h>
#include <unistd.h>
#include "mpi.h"
int i,j,k;
int N = 36;
int cmp(const void * a, const void * b) {
if (*(int*)a < *(int*)b) return -1;
if (*(int*)a > *(int*)b) return 1;
else return 0;
}
void phase1(int *array, int N, int startIndex, int subArraySize, int *pivots, int p) {
// 對子數組進行局部排序
qsort(array + startIndex, subArraySize, sizeof(array[0]), cmp);
// 正則採樣
for (i = 0; i < p; i++) {
pivots[i] = array[startIndex + (i * (N / (p * p)))];
}
return;
}
void phase2(int *array, int startIndex, int subArraySize, int *pivots, int *partitionSizes, int p, int myId) {
int *collectedPivots = (int *) malloc(p * p * sizeof(pivots[0]));
int *phase2Pivots = (int *) malloc((p - 1) * sizeof(pivots[0])); //主元
int index = 0;
//收集消息,根進程在它的接受緩衝區中包含所有進程的發送緩衝區的連接。
MPI_Gather(pivots, p, MPI_INT, collectedPivots, p, MPI_INT, 0, MPI_COMM_WORLD);
if (myId == 0) {
qsort(collectedPivots, p * p, sizeof(pivots[0]), cmp); //對正則採樣的樣本進行排序
// 採樣排序後進行主元的選擇
for (i = 0; i < (p -1); i++) {
phase2Pivots[i] = collectedPivots[(((i+1) * p) + (p / 2)) - 1];
}
}
//發送廣播
MPI_Bcast(phase2Pivots, p - 1, MPI_INT, 0, MPI_COMM_WORLD);
// 進行主元劃分,並計算劃分部分的大小
for ( i = 0; i < subArraySize; i++) {
if (array[startIndex + i] > phase2Pivots[index]) {
//如果當前位置的數字大小超過主元位置,則進行下一個劃分
index += 1;
}
if (index == p) {
//最後一次劃分,子數組總長減掉當前位置即可得到最後一個子數組劃分的大小
partitionSizes[p - 1] = subArraySize - i + 1;
break;
}
partitionSizes[index]++ ; //劃分大小自增
}
free(collectedPivots);
free(phase2Pivots);
return;
}
void phase3(int *array, int startIndex, int *partitionSizes, int **newPartitions, int *newPartitionSizes, int p) {
int totalSize = 0;
int *sendDisp = (int *) malloc(p * sizeof(int));
int *recvDisp = (int *) malloc(p * sizeof(int));
// 全局到全局的發送,每個進程可以向每個接收者發送數目不同的數據.
MPI_Alltoall(partitionSizes, 1, MPI_INT, newPartitionSizes, 1, MPI_INT, MPI_COMM_WORLD);
// 計算劃分的總大小,並給新劃分分配空間
for ( i = 0; i < p; i++) {
totalSize += newPartitionSizes[i];
}
*newPartitions = (int *) malloc(totalSize * sizeof(int));
// 在發送劃分之前計算相對於sendbuf的位移,此位移處存放着輸出到進程的數據
sendDisp[0] = 0;
recvDisp[0] = 0; //計算相對於recvbuf的位移,此位移處存放着從進程接受到的數據
for ( i = 1; i < p; i++) {
sendDisp[i] = partitionSizes[i - 1] + sendDisp[i - 1];
recvDisp[i] = newPartitionSizes[i - 1] + recvDisp[i - 1];
}
//發送數據,實現n次點對點通信
MPI_Alltoallv(&(array[startIndex]), partitionSizes, sendDisp, MPI_INT, *newPartitions, newPartitionSizes, recvDisp, MPI_INT, MPI_COMM_WORLD);
free(sendDisp);
free(recvDisp);
return;
}
void phase4(int *partitions, int *partitionSizes, int p, int myId, int *array) {
int *sortedSubList;
int *recvDisp, *indexes, *partitionEnds, *subListSizes, totalListSize;
indexes = (int *) malloc(p * sizeof(int));
partitionEnds = (int *) malloc(p * sizeof(int));
indexes[0] = 0;
totalListSize = partitionSizes[0];
for ( i = 1; i < p; i++) {
totalListSize += partitionSizes[i];
indexes[i] = indexes[i-1] + partitionSizes[i-1];
partitionEnds[i-1] = indexes[i];
}
partitionEnds[p - 1] = totalListSize;
sortedSubList = (int *) malloc(totalListSize * sizeof(int));
subListSizes = (int *) malloc(p * sizeof(int));
recvDisp = (int *) malloc(p * sizeof(int));
// 歸併排序
for ( i = 0; i < totalListSize; i++) {
int lowest = INT_MAX;
int ind = -1;
for (j = 0; j < p; j++) {
if ((indexes[j] < partitionEnds[j]) && (partitions[indexes[j]] < lowest)) {
lowest = partitions[indexes[j]];
ind = j;
}
}
sortedSubList[i] = lowest;
indexes[ind] += 1;
}
// 發送各子列表的大小回根進程中
MPI_Gather(&totalListSize, 1, MPI_INT, subListSizes, 1, MPI_INT, 0, MPI_COMM_WORLD);
// 計算根進程上的相對於recvbuf的偏移量
if (myId == 0) {
recvDisp[0] = 0;
for ( i = 1; i < p; i++) {
recvDisp[i] = subListSizes[i - 1] + recvDisp[i - 1];
}
}
//發送各排好序的子列表回根進程中
MPI_Gatherv(sortedSubList, totalListSize, MPI_INT, array, subListSizes, recvDisp, MPI_INT, 0, MPI_COMM_WORLD);
free(partitionEnds);
free(sortedSubList);
free(indexes);
free(subListSizes);
free(recvDisp);
return;
}
//PSRS排序函數,調用了4個過程函數
void psrs_mpi(int *array, int N)
{
int p, myId, *partitionSizes, *newPartitionSizes, nameLength;
int subArraySize, startIndex, endIndex, *pivots, *newPartitions;
char processorName[MPI_MAX_PROCESSOR_NAME];
MPI_Comm_size(MPI_COMM_WORLD,&p);
MPI_Comm_rank(MPI_COMM_WORLD,&myId);
MPI_Get_processor_name(processorName,&nameLength);
printf("Process %d is on %s\n",myId, processorName);
pivots = (int *) malloc(p*sizeof(int));
partitionSizes = (int *) malloc(p*sizeof(int));
newPartitionSizes = (int *) malloc(p*sizeof(int));
for ( k = 0; k < p; k++) {
partitionSizes[k] = 0;
}
// 獲取起始位置和子數組大小
startIndex = myId * N / p;
if (p == (myId + 1)) {
endIndex = N;
}
else {
endIndex = (myId + 1) * N / p;
}
subArraySize = endIndex - startIndex;
MPI_Barrier(MPI_COMM_WORLD);
//調用各階段函數
phase1(array, N, startIndex, subArraySize, pivots, p);
if (p > 1) {
phase2(array, startIndex, subArraySize, pivots, partitionSizes, p, myId);
phase3(array, startIndex, partitionSizes, &newPartitions, newPartitionSizes, p);
phase4(newPartitions, newPartitionSizes, p, myId, array);
}
if (myId == 0)
for(k = 0; k < N; k++){
printf("%d ",array[k]);
}
printf("\n");
if (p > 1) {
free(newPartitions);
}
free(partitionSizes);
free(newPartitionSizes);
free(pivots);
free(array);
MPI_Finalize();
}
int main(int argc, char *argv[]) {
int *array;
array = (int *) malloc(N*sizeof(int));
srand(100);
for ( k = 0; k < N; k++) {
array[k] = rand()%100;
}
MPI_Init(&argc,&argv); //MPI初始化
psrs_mpi(array,N); //調用PSRS算法進行並行排序
return 0;
}