This is a short package designed to help profile Rcpp packages based on the excellent advice from this blog post by Minimally Sufficient.
Rgperftools provides two functions start_profiler
and stop_profiler
, to be used as follows:
library(Rgperftools)
# Force devtools to compile without debug flags for optimal performance profiling
library(pkgbuild)
flags <- pkgbuild::compiler_flags(debug=FALSE)
new_compiler_flags <- function(debug=FALSE) {flags}
assignInNamespace('compiler_flags', new_compiler_flags, 'pkgbuild')
# Load your library
devtools::load_all()
# Collect profiling data
start_profiler("/tmp/profile.out")
run_your_cpp_stuff()
stop_profiler()
It can then be used with Google's pprof to visualize the profiler results in a convenient web interface.
pprof --http=localhost:[port_num] src/MyPackage.so /tmp/profile.out
Additional tips
-
You may need to type
~/go/bin/pprof
if you have not updated your$PATH
to include$GOPATH/bin
-
If you set
[port_num]
to 8899, you would navigate to http://localhost:8899 to view results -
For extra customization of compiler flags, replace the
new_compiler_flags
line with:new_compiler_flags <- function(debug=FALSE) {paste0(flags, " -O2 --some-other-flag")}
I recommend using the current Go version of pprof for results
visualization. This will require installing Go if you haven't already (instructions here), then running the following command to install pprof
to $GOPATH/bin/pprof
:
go install github.com/google/pprof@latest
Note that if $GOPATH
is not set, this will install to ~/go/bin/pprof
Next, you'll need to install the gperftools system library, then the Rgperftools R package:
Conda-based installation
Before installing, you must install gperftools, e.g with conda:
conda install -c conda-forge gperftools
Then to install, run:
# Set compiler variables, so we'll find the conda-based gperftools install
Sys.setenv(
CPATH=sprintf("%s:%s/include", Sys.getenv("CPATH"), Sys.getenv("CONDA_PREFIX")),
LIBRARY_PATH=sprintf("%s:%s/lib", Sys.getenv("CPATH"), Sys.getenv("CONDA_PREFIX"))
)
remotes::install_github("bnprks/Rgperftools")
apt-based installation (Debian/Ubuntu)
Before installing, you must install gperftools:
sudo apt install libgoogle-perftools-dev
Then to install, run:
remotes::install_github("bnprks/Rgperftools")