RcppEigen - going from inline to a .cpp function in a package and “Map”

自古美人都是妖i 提交于 2019-12-06 05:51:07

First question is whether this process for including an RcppEigen function into an existing R package is correct? (I completely ignored any Makevars files or any .h files -- I don't really know what they do... Also don't really understand the changes to the NAMESPACE file. I tried to copy the RcppEigen.package.skeleteon() set-up but I am adding my function to an existing package. So it would be good to know if it's okay in case I missed something that could be a problem later.)

For basic R packages with relatively simple C++ code, you do not need to include header files, or a custom Makevars / Makefile or anything like that. If you build something more complicated, you might need a Makefile / Makevars to help handle the build process, and might want to use header files to separate the interface from the implementation -- but for that you'll have to dive in the deep end and pick up some C++ books, because there's a lot to learn.

In other words -- what you're doing is perfectly fine. For simple cases, it's fine to just use .cpp files in the src/ directory (and let Rcpp, attributes, and its other sibling packages handle the rest)

Second question is whether I need a "Map" somewhere in rcppeigen_max_over_columns.cpp so that the matrix isn't copied when it's passed from R to C++?

Well, data will almost always be copied when transferring an R object to a (non-Rcpp) class, unless you specifically use a constructor that can re-use the underlying data. I am not aware of whether Eigen has a constructor that can re-use memory, but I would suggest that unless you know that it matters, don't worry about it (because copying a range of data is typically quite fast)

For the second question, it turns out this modification (thanks to my colleague Eric Lin) was all that was necessary, and it does seem to help, at least for benchmark examples of A <- matrix(rnorm(10000*100), 10000, 100). The max over columns is about 30 times faster than R with original cpp function, and 100 times faster than R using Eigen::Map.

Eigen::MatrixXd rcppeigen_max_over_columns(const Eigen::Map<Eigen::MatrixXd>  & A){
    Eigen::MatrixXd Amax = A.colwise().maxCoeff();
    return Amax;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!