一个包内的rcpp omp_set_num_threads [英] Rcpp omp_set_num_threads within a package
问题描述
我使用 Rcpp 和 OpenMP 编写了以下简单示例,当我从 RStudio 获取 cpp 文件时,该示例工作正常:
I wrote the following simple example with Rcpp and OpenMP that works fine when I source the cpp file from RStudio:
#include <Rcpp.h>
#include <omp.h>
// [[Rcpp::plugins(openmp)]]
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix my_matrix(int I, int J, int nthreads) {
NumericMatrix A(I,J);
int i,j,tid;
omp_set_num_threads(nthreads);
#pragma omp parallel for private(i, j, tid)
for(int i = 0; i < I; i++) {
for(int j = 0; j < J; j++) {
tid = omp_get_thread_num();
A(i,j) = tid ;
}
}
return A;
}
/*** R
set.seed(42)
my_matrix(10,10,5)
*/
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0 0 0 0 0 0 0 0 0 0
[2,] 0 0 0 0 0 0 0 0 0 0
[3,] 1 1 1 1 1 1 1 1 1 1
[4,] 1 1 1 1 1 1 1 1 1 1
[5,] 2 2 2 2 2 2 2 2 2 2
[6,] 2 2 2 2 2 2 2 2 2 2
[7,] 3 3 3 3 3 3 3 3 3 3
[8,] 3 3 3 3 3 3 3 3 3 3
[9,] 4 4 4 4 4 4 4 4 4 4
[10,] 4 4 4 4 4 4 4 4 4 4
但是,如果我创建了一个包,同样的代码就不会像预期的那样工作:
However, the same code does not work as expected if I create a package:
> rcpphello::my_matrix(10,10,5)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0 0 0 0 0 0 0 0 0 0
[2,] 0 0 0 0 0 0 0 0 0 0
[3,] 0 0 0 0 0 0 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0 0 0
[9,] 0 0 0 0 0 0 0 0 0 0
[10,] 0 0 0 0 0 0 0 0 0 0
如果我从包中调用它,为什么相同的代码只使用一个线程?如果有帮助,我将所有代码推送到 this github repo
Why is the same code only using one thread if I call it from within my package? In case it helps, I pushed all the code to this github repo
推荐答案
添加到 src/Makevars
和 src/Makevars.win
:
PKG_CXXFLAGS = $(SHLIB_OPENMP_CXXFLAGS)
PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS)
这会启用 -fopenmp
标志.否则,您最终将不会在您的软件包中启用 OpenMP.
This enables the -fopenmp
flag. Otherwise, you will not end up having OpenMP enabled in your package.
注意:使用时:
// [[Rcpp::plugins(openmp)]]
这会在使用 sourceCpp()
运行时设置 -fopenmp
参数 only.此选项不会转移到包中.因此,我们必须在Makevars
和Makevars.win
中建立设置.
This sets the -fopenmp
parameter only when run with sourceCpp()
. This option does not transfer into a package. Hence, we must establish the setting in Makevars
and Makevars.win
.
可以在这里找到一个简短的例子:
A short example can be found here:
https://github.com/r-pkg-examples/rcpp-and-openmp
不过,我需要稍微清理一下.
Though, I'll need to clean it up a bit.
这篇关于一个包内的rcpp omp_set_num_threads的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!