Search code examples
rshinyrcpp

Rcpp function takes a long time to compile


I wrote my first Rcpp function and am sourcing it with sourceCpp. It takes a long time, but not always (sometimes a couple seconds, but this is the typical):

system.time(sourceCpp('04_Rcpp_loads.cpp'))
   user  system elapsed 
   0.03    0.02   77.95

It processes a large dataframe very quickly, it's just slow to compile.

Here is my Rcpp function:

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector loads(NumericVector feet, double m1, double base_ft, double base_press, double SF) {
    int n = feet.size();
    double calc_0 = 0;
    double calc_1 = 0;
    double calc_2 = 0;
    double calc_3 = 0;
    double calc_4 = 0;
    double calc_5 = 0;
    double calc_6 = 0;
    double calc_7 = 0;
    NumericVector load_psf(n);

    for(int i = 0; i < n; ++i) {
        calc_0 = pow(2 * feet[i] / base_ft, 2.0);
        calc_1 = pow((pow(m1, 2.0) + calc_0) * (calc_0 + 1), 0.5);
        calc_2 = pow(m1, 2.0) + calc_0;
        calc_3 = 1 + calc_0;
        calc_4 = pow(m1, 2.0) + 2 * calc_0 + 1;
        calc_5 = (-2) * m1 * feet[i] / base_ft;
        calc_6 = pow(m1, 2.0) + calc_0 + 1;
        calc_7 = asin(m1 / calc_1);
        load_psf[i] = 2 * base_press * SF *((calc_5 / pow(calc_6, 0.5)) * calc_4 / (calc_3 * calc_2) + calc_7) / 3.14159265;
    }
    return load_psf;   
}

The function is used in an app on shinyapps.io. I don't know what is happening there, but it takes a long time to start up the app, so I suspect the same thing. The output above is directly from RStudio on my Windows machine. All packages updated to latest version as of this posting.

I suspect there is a way I can make this faster - by pre-compiling it perhaps? How do I make this faster? And when I do, how will I run it on shinyapps.io?


Solution

  • Couple of quick points:

    1. If you make your function part of a package, it is compiled once 'off-line' and you can just load it, which is essentially "free" in terms of resourse use.. That is what I would do.

    2. There are compilation options as you can now choose between headers Rcpp/Rcpp, Rcpp/Light, Rcpp/Lighter and Rcpp/Lightest (which choose how many optional Rcpp features are included.

    3. Compilation is known to be expensive. Where possible, I always try to rely on cached compilation via ccache -- see this blog post of mine for more.

    Hope this helps. Happy to discuss more, maybe on the rcpp-devel list.