[Rcpp-devel] Idiom for accessing scalars

Dirk Eddelbuettel edd at debian.org
Fri Jan 6 19:15:05 CET 2012


On 6 January 2012 at 13:00, Steve Lianoglou wrote:
| Hi,
| 
| 2012/1/6 Douglas Bates <bates at stat.wisc.edu>:
| [snip]
| > As I mentioned in another thread, I prefer the idiom
| >
| > int n2 = ::Rf_asInteger(n);
| >
| > because asInteger is part of the R API (in Rcpp it must be called as
| > Rf_asInteger - the :: is a hint to the compiler that it will be found
| > in the global namespace).  Functions like asInteger and asReal are
| > used in thousands of places in the base R code and have been optimized
| > to death as well as being as general as they can possibly be.
| 
| Cool ... I actually missed that tip, thanks for pointing it out again.

And if one overcomes the "ick" factor of mixing APIs <grin>, it saves a
little:

R> library(inline)
R> library(microbenchmark)
R> 
R> fr <- cxxfunction(signature(xs="integer"), plugin="Rcpp", body='
+    int x = ::Rf_asInteger(xs);
+    return Rcpp::wrap(x);
+ ')
R> 
R> frcpp <- cxxfunction(signature(xs="integer"), plugin="Rcpp", body='
+    int x = Rcpp::as<int>(xs);
+    return Rcpp::wrap(x);
+ ')
R> 
R> microbenchmark(fr(123), frcpp(123))
Unit: nanoseconds
        expr min    lq median   uq   max
1    fr(123) 841 878.5  908.5  976 15684
2 frcpp(123) 976 999.5 1017.0 1085  6589
R>  

A good chunk here is "fixed" cost of calling a function, returning a
value, ... so that the "variable" gain of ::Rf_asInteger() looks pretty good.

Dirk, somewhat wondering why we're debating 100ns gains in the context of R

-- 
"Outside of a dog, a book is a man's best friend. Inside of a dog, it is too
dark to read." -- Groucho Marx


More information about the Rcpp-devel mailing list