Search code examples
c++rprofilingrcppgperftools

How to profile Rcpp code (on linux)


I made an R package with Rcpp where whole simulations are run in c++ and results are analyzed in R. Now I need to profile my functions so I can optimize them, but R profilers can't distinguish what happens inside the C++ functions, and I don't know how to run C++ profilers when the functions can only be ran from inside R.

So far, I have found some suggestions to use gperftools (questions and tutorials) but the guides are incomplete (maybe they assume a level of knowledge that I lack?), have missing links, and I keep running into walls. Hence this question. Here's where I'm at:

  1. Install gperftools (I installed from extra/gperftools with pacman)
  2. include gperftools/profiler.h on the C++ header
  3. Add ProfilerStart("myprof.log") and ProfilerStop() in the C++ code around what I want to profile
  4. Compile with -lprofiler
  5. Run "$ CPUPROFILE="myprof.log" R -f myscript.R"

The current wall is gcc tells me "Undefined Symbol: ProfilerStart", so I think there's something wrong with the linking?


Solution

  • It was a linking error after all, caused by my lack of experience as this is the first time I use Makevars. In step #4, I added "-lprofiler" to PKG_CXXFLAGS, that is used in compiling, when I should have added it to PKG_LIBS. I made the change and now the profiler works just fine. This is my Makevars now:

    PKG_CXXFLAGS += -Wall -pedantic -g -ggdb #-fno-inline-small-functions PKG_LIBS += -lprofiler CXX_STD = CXX11