
Last chance! 50% off unlimited learning
Sale ends in
microbenchmark
serves as a more accurate replacement of the
often seen system.time(replicate(1000, expr))
expression. It tries hard to accurately measure only the time it
takes to evaluate expr
. To achieved this, the
sub-millisecond (supposedly nanosecond) accurate timing functions
most modern operating systems provide are used. Additionally all
evaluations of the expressions are done in C code to minimize any
overhead.
microbenchmark(..., list = NULL, times = 100L, unit, check = NULL,
control = list())
Expressions to benchmark.
List of unevaluated expression to benchmark.
Number of times to evaluate the expression.
Default unit used in summary
and print
.
Function to check if the expressions are equal. By default NULL
which omits the check.
List of control arguments. See Details.
Object of class ‘microbenchmark’, a data frame with
columns expr
and time
. expr
contains the
deparsed expression as passed to microbenchmark
or the name
of the argument if the expression was passed as a named
argument. time
is the measured execution time of the
expression in nanoseconds. The order of the observations in the
data frame is the order in which they were executed.
This function is only meant for micro-benchmarking small pieces of source code and to compare their relative performance characteristics. You should generally avoid benchmarking larger chunks of your code using this function. Instead, try using the R profiler to detect hot spots and consider rewriting them in C/C++ or FORTRAN.
The control
list can contain the following entries:
the order in which the expressions are evaluated. “random” (the default) randomizes the execution order, “inorder” executes each expression in order and “block” executes all repetitions of each expression as one block.
the number of warm-up iterations performed before the actual benchmark. These are used to estimate the timing overhead as well as spinning up the processor from any sleep or idle states it might be in. The default value is 2.
print.microbenchmark
to display and
boxplot.microbenchmark
or
autoplot.microbenchmark
to plot the results.
# NOT RUN {
## Measure the time it takes to dispatch a simple function call
## compared to simply evaluating the constant \code{NULL}
f <- function() NULL
res <- microbenchmark(NULL, f(), times=1000L)
## Print results:
print(res)
## Plot results:
boxplot(res)
## Pretty plot:
if (require("ggplot2")) {
autoplot(res)
}
## Example check usage
my_check <- function(values) {
all(sapply(values[-1], function(x) identical(values[[1]], x)))
}
f <- function(a, b)
2 + 2
a <- 2
## Check passes
microbenchmark(2 + 2, 2 + a, f(2, a), f(2, 2), check=my_check)
# }
# NOT RUN {
a <- 3
## Check fails
microbenchmark(2 + 2, 2 + a, f(2, a), f(2, 2), check=my_check)
# }
Run the code above in your browser using DataLab