Search code examples
rperformancesubroutinemicrobenchmark

How to microbenchmark subroutines in R?


I have programmed an R function f that calls subroutines f1 and f2. Say

f1 <- function() Sys.sleep(0.1)
f2 <- function() Sys.sleep(0.2)

f <- function(){
  f1()
  f2()
}

I want to benchmark the performance of f and its subroutines in order to find out which subroutine can be improved regarding the runtime. Unfortunately microbenchmark only gives the runtime of f:

microbenchmark(f(), times = 10) # gives
Unit: milliseconds
 expr      min       lq     mean   median       uq      max neval
  f() 302.0776 309.7246 312.5698 312.9659 314.0021 327.6248    10

I would like to have statistics for the subroutines called in f. Something like

Unit: milliseconds
 expr      min       lq     mean   median       uq      max neval
 f1() 100.0000 107.0000 115.0000 115.0000 117.0000 127.0000    10
 f2() 202.0000 209.0000 212.0000 212.0000 214.0000 227.0000    10

Solution

  • As also outlined in the comments, profiling your function is the way to find out the time of the subroutines. The package that is mentioned from Hadley Wickham is deprecated in favor of profvis, so I think profvis is the one to go for.