猿代码 — 科研/AI模型/高性能计算
0

MPI环境测试经典程序:PI的计算

摘要: #includestdio.h#includestring.h#includempi.h#pragma warning(disable : 4996)#define MAX_STRING 100using namespace std;#include fstream#include ctime#include iostream#define random() (rand() / double (R ...
#include<stdio.h>
#include<string.h>
#include<mpi.h>
#pragma warning(disable : 4996)
#define MAX_STRING 100
using namespace std;
#include <fstream>
#include <ctime>
#include <iostream>

#define random() (rand() / double (RAND_MAX) * 2 - 1)

int main(void) {
int comm_sz;
int my_rank;
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

// 只有一个线程的时候不操作
if (comm_sz <= 1) {
MPI_Finalize();
return 0;
}
long long int count_time; // 总的计算次数
long long int Cal[2] = { 0 };
if (my_rank == 0) {
ifstream cin("D:\\C++\\VS\\repo\\MPI-DEMO\\MPI-DEMO\\input.txt");
cin >> count_time;
long long int tempCal[2] = { 0 };

long long int width = count_time / (comm_sz - 1);
long long int reminder = count_time % (comm_sz - 1);
long long int temp_count_time;
for (int i = 1; i < comm_sz; ++i)
{
temp_count_time = width;
if (i <= reminder) temp_count_time++;
MPI_Send(&temp_count_time, 1, MPI_LONG_LONG_INT, i, 0, MPI_COMM_WORLD);
}
for (int i = 1; i < comm_sz; ++i)
{
MPI_Recv(tempCal, 2, MPI_LONG_LONG_INT, i, 0, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);
for (int j = 0; j < 2; ++j) { Cal[j] += tempCal[j]; }
}

std::cout << 4.0 * Cal[0] / count_time << endl;
} // 运算的子节点
else {
srand((unsigned)time(NULL));
MPI_Recv(&count_time, 1, MPI_LONG_LONG_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);
Cal[1] = count_time;
Cal[0] = 0;
double x, y, dst;
for (int i = 0; i < count_time; ++i) {
x = random();
y = random();
dst = x * x + y * y;
if (dst <= 1) Cal[0] += 1;
}
MPI_Send(Cal, 2, MPI_LONG_LONG_INT, 0, 0, MPI_COMM_WORLD);
}
MPI_Finalize();
return 0;
}

说点什么...

已有0条评论

最新评论...

本文作者
2024-1-25 16:36
  • 0
    粉丝
  • 324
    阅读
  • 0
    回复
资讯幻灯片
热门评论
热门专题
排行榜
Copyright   ©2015-2023   猿代码-超算人才智造局 高性能计算|并行计算|人工智能      ( 京ICP备2021026424号-2 )