資源簡介
使用c++語言編寫的MPI并行優化N-body問題源碼,測試可用。適用于剛開始接觸并行計算解決基本問題的人,可作為參考。
代碼片段和文件信息
//mpi_nbody_basic.c,MPI?基本算法
#include?
#include?
#include?
#include?
#include?
#define?OUTPUT??????????????????????????//?要求輸出結果
#define?DEBUG???????????????????????????//?debug?模式,每個函數給出更多的輸出
#define?DIM?????2???????????????????????//?二維系統
#define?X???????0???????????????????????//?X?坐標
#define?Y???????1???????????????????????//?Y?坐標
typedef?double?vect_t[DIM];?????????????//?向量數據類型
const?double?G?=?6.673e-11;?????????????//?萬有引力常量
int?my_rank?comm_sz;???????????????????//?進程編號和總進程數
MPI_Datatype?vect_mpi_t;????????????????//?使用的派生數據類型
vect_t?*vel?=?NULL;?????????????????????//?全局顆粒速度,用于?0?號進程的輸出
void?Usage(char*?prog_name)//?輸入說明
{
fprintf(stderr?“usage:?mpiexec?-n??%s\n“?prog_name);
fprintf(stderr?“????\n“);
fprintf(stderr?“????‘g‘:?inite?condition?by?random\n“);
fprintf(stderr?“????‘i‘:?inite?condition?from?stdin\n“);
exit(0);
}
void?Get_args(int?argc?char*?argv[]?int*?n_p?int*?n_steps_p?double*?delta_t_p?int*?output_freq_p?char*?g_i_p)//?獲取參數信息
{?????????????????????????????????????????????????????????????????????//?所有進程均調用該函數,因為有集合通信,但只有?0?號進程處理參數
if?(my_rank?==?0)
{
if?(argc?!=?6)
Usage(argv[0]);
*n_p?=?strtol(argv[1]?NULL?10);
*n_steps_p?=?strtol(argv[2]?NULL?10);
*delta_t_p?=?strtod(argv[3]?NULL);
*output_freq_p?=?strtol(argv[4]?NULL?10);
*g_i_p?=?argv[5][0];
if?(*n_p?<=?0?||?*n_p?%?comm_sz?||?*n_steps_p?0?||?*delta_t_p?<=?0?||?*g_i_p?!=?‘g‘?&&?*g_i_p?!=?‘i‘)//?不合要求的輸入情況
{
printf(“haha\n“);
if?(my_rank?==?0)
Usage(argv[0]);
MPI_Finalize();
exit(0);
}
}
MPI_Bcast(n_p?1?MPI_INT?0?MPI_COMM_WORLD);
MPI_Bcast(n_steps_p?1?MPI_INT?0?MPI_COMM_WORLD);
MPI_Bcast(delta_t_p?1?MPI_DOUBLE?0?MPI_COMM_WORLD);
MPI_Bcast(output_freq_p?1?MPI_INT?0?MPI_COMM_WORLD);
MPI_Bcast(g_i_p?1?MPI_CHAR?0?MPI_COMM_WORLD);
#???ifdef?DEBUG//?確認各進程中的參數情況
printf(“Get_args?rank%2d?n?%d?n_steps?%d?delta_t?%e?output_freq?%d?g_i?%c\n“
my_rank?*n_p?*n_steps_p?*delta_t_p?*output_freq_p?*g_i_p);
fflush(stdout);
#???endif
}
void?Gen_init_cond(double?masses[]?vect_t?pos[]?vect_t?loc_vel[]?int?n?int?loc_n)//?自動生成初始條件,所有進程均調用該函數,因為有集合通信
{??????????????????????????????????????????????????????????//?生成的顆粒位于原點和?X?正半軸,速度大小相等,方向平行于?Y?軸,交錯向上下
const?double?mass?=?5.0e24?gap?=?1.0e5?speed?=?3.0e4;//?使用了地球的質量和公轉速度
if?(my_rank?==?0)
{
//?srand(2);//?使用隨機方向和速度大小,下同
for?(int?i?=?0;?i? {
masses[i]?=?mass;
pos[i][X]?=?i?*?gap;
pos[i][Y]?=?0.0;
vel[i][X]?=?0.0;
//?vel[i][Y]?=?speed?*?(2?*?rand()?/?(double)RAND_MAX)?-?1);
vel[i][Y]?=?(i?%?2)???-speed?:?speed;
}
}
//?同步質量,位置信息,分發速度信息
MPI_Bcast(masses?n?MPI_DOUBLE?0?MPI_COMM_WORLD);
MPI_Bcast(pos?n?vect_mpi_t?0?MPI_COMM_WORLD);
MPI_Scatter(vel?loc_n?vect_mpi_t?loc_vel?loc_n?vect_mpi_t?0?MPI_COMM_W
- 上一篇:三子連珠游戲VC++程序
- 下一篇:圖像相似度比較
評論
共有 條評論