zoukankan      html  css  js  c++  java
  • 【MPI】并行求和

    比较简单的并行求和 读入还是串行的 而且无法处理线程数无法整除数据总长度的情况

    主要用到了MPI_Bcast MPI_Scatter MPI_Reduce

    typedef long long __int64;
    #include "mpi.h"
    #include <cstdio>
    #include <cmath>
    using namespace std;
    int main(int argc, char* argv[]){
        int my_rank=0, comm_sz=0, local_int=0, total_int=0;
        MPI_Init(&argc, &argv);
        MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
        MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
        int *a,*local_a;
        int n;
        if(my_rank==0){
            scanf("%d",&n);
        }
        MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD);
        local_a=new int[n/comm_sz];
        if(my_rank==0){
            a=new int[n];
            for(int i=0;i<n;++i){
                scanf("%d",&a[i]);
            }
            MPI_Scatter(a,n/comm_sz,MPI_INT,local_a,n/comm_sz,MPI_INT,0,MPI_COMM_WORLD);
            delete[] a;
        }
        else{
            MPI_Scatter(a,n/comm_sz,MPI_INT,local_a,n/comm_sz,MPI_INT,0,MPI_COMM_WORLD);
        }
        for(int i=0;i<n/comm_sz;++i){
            local_int+=local_a[i];
        }
        delete[] local_a;
        MPI_Reduce(&local_int,&total_int,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD);
        if (my_rank == 0)
        {
            printf("%d个线程,每份长度为%d,结果为%d
    ", comm_sz, n/comm_sz, total_int);
    
        }
        MPI_Finalize();
        return 0;
    }
  • 相关阅读:
    内网Windows Server时间自动同步
    处理sqlserver数据
    virtualenv使用
    vue过渡动画效果
    vue视图
    vue组件
    Vue实例
    vue介绍
    Bootstrap布局
    Bootstrap组件
  • 原文地址:https://www.cnblogs.com/autsky-jadek/p/8143970.html
Copyright © 2011-2022 走看看