gpt4 book ai didi

c++ - 使用MPI在c++中并行for循环

转载 作者:行者123 更新时间:2023-12-02 14:56:53 29 4
gpt4 key购买 nike

我试图在 C++ 中使我的 for 循环并行。迭代是完全独立的。下面是一个类似的程序,它捕捉了任务的想法。

class A{

// create experiment
// perform experiment
// append results to file
// reset the experiment

};

main {

// open a file

// instance class
A a;
int N = 10000;

for ( int i = 0; i <= N; i++ ){
a.do_something()
}

// close file
// return
}

每次迭代都会简单地将其数据打印到输出文件中,顺序也不重要。由于 a.do_something() 很长,我想让它并行。我已经安装了 MPI,现在对它的基本用法有些熟悉了。

我的逻辑是根据可用处理器的数量将范围 N 分成多个分区。我正在寻找有关如何使我的串行版本与 MPI 并行的帮助。我的尝试是:

class A{

// create experiment
// perform experiment
// append results to file
// reset the experiment

};

main {

// open a file

// instance class
A a;


// initialise the MPI
int ierr = MPI_Init(&argc, &argv);
int procid, numprocs;

ierr = MPI_Comm_rank(MPI_COMM_WORLD, &procid);
ierr = MPI_Comm_size(MPI_COMM_WORLD, &numprocs);

// partition = (job size) over (processors).
unsigned int partition = N / numprocs;


int N = 10000;

for ( int i = 0; i <= N; i++ ){
a.do_something()
}



ierr = MPI_Finalize();
// close file
// return
}

但我真的很难拆分 for 循环,不知道如何进行。

这只会运行串行代码两次(在我的双核机器上)。我想将 for 循环拆分为 N/2 block ,并让每个线程处理不同的 block 。

我是否需要保留一个核心来将作业广播到其他核心?我可以遍历分区吗?我在网上搜索过,但运气不佳。有什么建议么?

最佳答案

当代码的 MPI 部分开始时,将其视为在处理器上运行的独立程序。这意味着您编写的循环在两个处理器上独立运行。例如,一种拆分它的方法是

for ( int i = rank*partition; i <= rank*partition+partition; i++ )

{
a.do_something()
}

此外,在使用 N 之前声明 N :-)

关于c++ - 使用MPI在c++中并行for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52496748/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com