⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 20070429.cpp

📁 c++ 并行计算程序
💻 CPP
字号:
#include "mpi.h"
#include <stdio.h>
#include <math.h>
#include "stdlib.h"

int main(int argc,char *argv[])
{
    int done = 0, n, myid, numprocs;
    int i,row,col;
    double startwtime = 0.0, endwtime;
    int  namelen;
    char processor_name[MPI_MAX_PROCESSOR_NAME];
	bool HaveData=false;

    MPI_Init(&argc,&argv);
    MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD,&myid);
    MPI_Get_processor_name(processor_name,&namelen);
	MPI_Status status;

    fprintf(stdout,"进程 %d 总 %d 运行在计算机 %s 上\n",myid, numprocs, processor_name);
    fflush(stdout);    

    while (!done) 
	{
	
        if (myid == 0) 
		{
            fprintf(stdout, "请输入矩阵维数: (0 退出) ");			
			fflush(stdout);
			scanf("%d",&n);
            startwtime = MPI_Wtime();
        }
        MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
        if (n == 0)
		{
            done = 1;
			printf("----系统已退出计算----\n" );
			break;
		}
        else 
		{
            // 重新定义矩阵维数
			int **A=new int*[n];			
			int **B=new int*[n];
			int **C=new int*[n];
			for(i=0;i<n;i++)
			{
				A[i]=new int[n];
				B[i]=new int[n];
				C[i]=new int[n];
			}			
			// 初始化矩阵元素
			for(row=0;row<n;row++)
			{
				for(col=0;col<n;col++)
				{
					A[row][col]=2;
					B[row][col]=0;
					C[row][col]=0;
				}
			}
			
			for(row=myid;row<n;row+=numprocs)
			{
				for(col=0;col<n;col++)
				{
					for(i=0;i<n;i++)
					{
						C[row][col]+=A[row][i]*A[i][col];
					}					
				}
			}
			if(numprocs>1)
			{ 
				for(row=0;row<n;row++)
					MPI_Reduce(&C[row][0], &B[row][0], n, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
			}
			else
			{
				for(row=0;row<n;row++)
				{
					for(col=0;col<n;col++)
						B[row][col]=C[row][col];
				}
				
			}
            

            if (myid == 0) 
			{
                endwtime = MPI_Wtime();
				printf("计算耗时: = %f\n", endwtime-startwtime);
				printf("===============================================\n");
				//for(row=0;row<n;row++)
				//{
				//	for(col=0;col<n;col++)
				//		printf("%d  ",B[row][col]);
				//	printf("\n");
				//}
				fflush( stdout );
			}
        }
    }
    MPI_Finalize();
    return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -