[R] quoted expressions in microbenchmark

Prof J C Nash (U30A) nashjc at uottawa.ca
Mon Sep 2 17:57:47 CEST 2013


I use microbenchmark to time various of my code segments and find it 
very useful. However, by accident I called it with the expression I 
wanted to time quoted. This simply measured the time to evaluate the 
quote. The following illustrates the difference. When explained, the 
issue is obvious, but I spun some wheels for a while and the example may 
help others.

 > rm(list=ls()) # clear workspace
 > genrose.g <- function(x, gs=100){
 > # vectorized gradient for genrose.f
 > n <- length(x)
 > gg <- as.vector(rep(0, n))
 > tn <- 2:n
 > tn1 <- tn - 1
 > z1 <- x[tn] - x[tn1]^2
 > z2 <- 1 - x[tn]
 > gg[tn] <- 2 * (gs * z1 - z2)
 > gg[tn1] <- gg[tn1] - 4 * gs * x[tn1] * z1
 > return(gg)
 > }
 > require(microbenchmark)
 > trep=1000
 > xx<-rep(pi/2,20)
 > atq<-microbenchmark("genrose.g(xx)", times=trep)
 > print(atq)
 > at<-microbenchmark(genrose.g(xx), times=trep)
 > print(at)

which gives

 > source("tmbench.R")
Unit: nanoseconds
             expr min  lq median  uq   max neval
  "genrose.g(xx)"  70 420    489 489 12851  1000
Unit: microseconds
           expr    min     lq median     uq      max neval
  genrose.g(xx) 47.982 49.868 50.426 51.404 3523.566  1000

Thanks to Olaf Mersmann for a quick response to set me straight. He 
pointed out that sometimes one wants to measure the time to evaluate a 
character string, as in the following.

   > microbenchmark(NULL, "", "asdf", "12345678901234567890", times=1000L)
   Unit: nanoseconds
                      expr min lq median uq max neval
                      NULL  24 25     28 29 161  1000
                        ""  24 25     28 29 121  1000
                    "asdf"  24 25     28 29 161  1000
    "12345678901234567890"  24 28     28 29 542  1000


John Nash



More information about the R-help mailing list