I have been working my way through Dirk Eddelbuettel's Rcpp
tutorial here:
http://www.rinfinance.com/agenda/
I have learned how to save a C++ file in a directory and call it and run it from within R. The C++ file I am running is called 'logabs2.ccp' and its contents are directly from one of Dirk's slides:
#include <Rcpp.h>
using namespace Rcpp;
inline double f(double x) { return ::log(::fabs(x)); }
// [[Rcpp::export]]
std::vector<double> logabs2(std::vector<double> x) {
std::transform(x.begin(), x.end(), x.begin(), f);
return x;
}
I run it with this R code:
library(Rcpp)
sourceCpp("c:/users/mmiller21/simple r programs/logabs2.cpp")
logabs2(seq(-5, 5, by=2))
# [1] 1.609438 1.098612 0.000000 0.000000 1.098612 1.609438
I am running the code on a Windows 7 machine from within the R GUI that seems to install by default. I also installed the most recent version of Rtools
. The above R code seems to take a relatively long time to run. I suspect most of that time is devoted to compiling the C++ code and that once the C++ code is compiled it runs very quickly. Microbenchmark
certainly suggests that Rcpp
reduces computation time.
I have never used C++ until now, but I know that when I compile C code I get an *.exe file. I have searched my hard-drive from a file called logabs2.exe
but cannot find one. I am wondering whether the above C++ code might run even faster if a logabs2.exe
file was created. Is it possible to create a logabs2.exe
file and store it in a folder somewhere and then have Rcpp call that file whenever I wanted to use it? I do not know whether that makes sense. If I could store a C++ function in an *.exe file then perhaps I would not have to compile the function every time I wanted to use it with Rcpp and then perhaps the Rcpp code would be even faster.
Sorry if this question does not make sense or is a duplicate. If it is possible to store the C++ function as an *.exe file I am hoping someone will show me how to modify my R code above to run it. Thank you for any help with this or for setting me straight on why what I suggest is not possible or recommended.
I look forward to seeing Dirk's new book.
R CMD SHLIB
? With that you can just compile your C++ function to a dll file and then load the compiled file withdyn.load()
. Have a look at?SHLIB
and?dyn.load
for details! – user1981275