c - 如何根据 CMake 变量拥有一个串行和并行工作的代码
问题描述
CMake 的摘录显示了我如何定义PARALLEL
要传递到代码中的标志:
option(ENABLE_MPI "Enable MPI parallelization" OFF)
SET(PARALLEL 0 CACHE INTEGER "Defines a Parallel Build")
if(ENABLE_MPI)
find_package(MPI REQUIRED)
include_directories(${MPI_INCLUDE_PATH})
set(CMAKE_C_FLAGS "${CMAKE_FLAGS} ${MPI_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${MPI_CXX_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${MPI_EXE_LINKER_FLAGS}")
add_subdirectory(third-party/parmetis-4.0.3)
unset(PARALLEL CACHE)
SET(PARALLEL 1 CACHE INTEGER "Defines a Parallel Build")
add_definitions( -DPARALLEL=${PARALLEL} )
endif(ENABLE_MPI)
在我的 C 代码中,我有一个这样的选项:
#ifndef PARALLEL
# define PARALLEL @PARALLEL@
#endif
int main(int argc, char **argv){
int world_rank =0;
int world_size=0;
if (PARALLEL) {
printf("This is a parallel build!\n");
// Initialize the MPI environment
MPI_Init(NULL, NULL);
// Get the number of processes
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
// Get the rank of the process
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
// Get the name of the processor
char processor_name[MPI_MAX_PROCESSOR_NAME];
int name_len;
MPI_Get_processor_name(processor_name, &name_len);
// Print off a hello world message
printf("Hello world from processor %s, rank %d out of %d processors\n",
processor_name, world_rank, world_size);
if (world_rank == 0) {
//read inputfile and initalize
printf("rank ID %d\n",world_rank);
}
}
else {
printf("This is NOT a parallel build!\n");
}
if (world_rank == 0) {
//read inputfile and initalize
printf("rank ID %d: Read Inputfile \n",world_rank);
if (PARALLEL) {
printf("rank ID %d: Parition Mesh with %d Partitions\n",world_rank,world_size);
}else{printf("rank ID %d: Serial Simulation - No Mesh Partitioning \n", world_rank); }
}
//ReadInputFile(argv[1]);
//WriteVTU(argv[1]);
//FreeArrays();
if (PARALLEL) {
// Finalize the MPI environment.
MPI_Finalize();
}
return 0;
}
我从中得到的输出(使用并行构建)是:
This is a parallel build!
Hello world from processor -----, rank 0 out of 2 processors
rank ID 0
rank ID 0: Read Inputfile
rank ID 0: Parition Mesh with 0 Partitions
This is a parallel build!
Hello world from processor ----, rank 1 out of 2 processors
rank ID 0: Read Inputfile
rank ID 0: Parition Mesh with 0 Partitions
有没有办法编写可以串行编译(比如使用 cc)和并行编译(使用 mpicc)的单个程序?
解决方案
推荐阅读
- laravel - 如何在运行时模拟和测试没有迁移模式的模型
- python - 根据文件名中嵌入的时间戳对文件进行排序、分组和处理
- python - 如何将值(时间格式)转换为数字(浮点数)
- node.js - 如何在nodejs项目中动态加载页面内的数据?
- wpf - WPF-如何在单击树视图超链接时重新加载同一页面
- python - keras中的多图像输入
- ios - 初始化而不在swift中传递任何参数?
- wpf - RenderTransformOrigin 中的更改导致旋转的 UI 元素中的平移
- wix - 自定义操作更改 InstallPrivileges
- firebase - 如何使用固定后缀进行动态链接