Using the Rcpp Timer

January 6, 2013

(This article was first published on Rcpp Gallery, and kindly contributed to R-bloggers)

Sine the 0.10.2 release, Rcpp contains an internal class Timer which can be used for fine-grained benchmarking. Romain motivated Timer in a post to the mailing * list where Timer is used to measure the different components of the costs of random number generation.

A slightly modified version of that example follows below.

#include <Rcpp.h>
#include <Rcpp/Benchmark/Timer.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector useTimer() {
    int n = 1000000;

    // start the timer
    Timer timer;
    for(int i=0; i<n; i++) {
    timer.step("get/put") ;

    for(int i=0; i<n; i++) {
        rnorm(10, 0.0, 1.0);

    for(int i=0; i<n; i++) {
        // empty loop
    timer.step( "empty loop" ) ;

    NumericVector res(timer);
    for (int i=0; i<res.size(); i++) {
        res[i] = res[i] / n;
    return res;

We get the following result, each expressing the cost per iteration in nanoseconds:

    get/put g/p+rnorm()  empty loop 
  1.634e+03   2.573e+03   2.620e-04 

The interesting revelation is that repeatedly calling GetRNGstate() and PutRNGstate() can amount to about 60% of the cost of RNG draws. Luckily, we usually only have to call these helper functions once per subroutine called from R (rather than repeatedly as shown here) so this is not really a permanent cost to bear when running simulations with R.

It also show the usefulness of a fine-grained timer at the code level.

To leave a comment for the author, please follow the link and comment on their blog: Rcpp Gallery. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Mango solutions

RStudio homepage

Zero Inflated Models and Generalized Linear Mixed Models with R

Dommino data lab

Quantide: statistical consulting and training



CRC R books series

Six Sigma Online Training

Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)