[Rcpp-devel] Cost of function pointer dereferencing

romain at r-enthusiasts.com romain at r-enthusiasts.com
Thu Dec 23 17:45:15 CET 2010


Hello, 

Since I've been playing with efficiency of various operators for numeric vectors (+,-,/,*), I'm now looking at other functions such as exp, sqrt, etc ...

The way we currently implement exp for vectors requires that we keep a function pointer for the atomic exp and that we dereference the function pointer each time. It turns out that this has some cost : 

     test replications elapsed relative user.self sys.self user.child sys.child
1  static            1   0.691  1.00000     0.691    0.000          0         0
2 pointer            1  11.157 16.14616    11.144    0.012          0         0

Reproduced by this code: 

require( Rcpp )
require( inline )

fx <- cxxfunction( , '
double x ;
for( int j=0; j<1000; j++){
for( int i=0; i<1000000; i++){
    x = exp(2.0) ; 
}
}
return wrap( x ) ;
', plugin = "Rcpp" )

inc <- '
    double (*fun)(double) = exp ;
'
fy <- cxxfunction( , '
double x ;
for( int j=0; j<1000; j++){
for( int i=0; i<1000000; i++){
    x = (*fun)(2.0) ; 
}
}
return wrap( x ) ;
', plugin = "Rcpp", includes = inc )


require( rbenchmark )
benchmark( 
    order = "relative", 
    static = fx(), 
    pointer = fy(),
    replications = 1L
)

Romain






More information about the Rcpp-devel mailing list