ZetCode

R performance and profiling

last modified November 20, 2026

R is interpreted, but most of its built-in functions run in compiled C code. A script is fast when it hands whole vectors to those functions and slow when it runs an explicit R loop over millions of elements. Performance work starts with measurement: find the part that dominates the run time, change one thing, and measure again. This article covers system.time, proc.time, vectorization, preallocation, Rprof, microbenchmark, and byte compilation with compiler. The examples use R 4.5.2 and microbenchmark 1.5.0. The timings are from one run on the test machine; absolute values vary between runs and machines.

The examples need the microbenchmark package, which is not part of base R. Install it once with install.packages("microbenchmark"); the installing packages section of the introduction explains the details.

Measuring elapsed time

proc.time() returns the user, system, and elapsed times of the current R process. The elapsed component is wall-clock time, while user and system measure CPU time. system.time(expr) is a wrapper that evaluates an expression and returns the same five numbers. The first script measures a loop and prints the structure of the result; the elapsed value itself is discussed in the text because it changes from run to run.

timing.R
total <- 0
start <- proc.time()
for (i in 1:200000) {
  total <- total + i
}
elapsed <- proc.time() - start
cat("total:", total, "\n")
cat("elapsed class:", class(elapsed), "\n")
cat("elapsed names:", paste(names(elapsed), collapse = ", "), "\n")

The loop adds 200000 numbers and prints 20000100000. The result of proc.time() - start has class proc_time and five components: user.self, sys.self, elapsed, user.child, and sys.child. The first three describe this process; the last two describe child processes. On the test machine the elapsed component was about 0.01 seconds, which is small enough that process startup dominates the measurement. system.time is easier to read at the console but returns the same object.

$ Rscript timing.R
total: 20000100000 
elapsed class: proc_time 
elapsed names: user.self, sys.self, elapsed, user.child, sys.child 

Vectorized versus loop

A vectorized function receives the whole vector and loops in C. An explicit R loop pays the interpreter cost for every element. The next script builds a vector of ten million numbers, sums its square roots with a loop, then with sum(sqrt(values)). Both expressions compute the same value; only the second hands the loop to compiled code. The script computes both times but prints only the comparison, because the times differ from run to run.

vectorized.R
n <- 10000000
values <- as.numeric(seq_len(n))
loop_sum <- function(x) {
  total <- 0
  for (i in seq_along(x)) {
    total <- total + sqrt(x[i])
  }
  total
}
loop_time <- system.time(loop_total <- loop_sum(values))[["elapsed"]]
vector_time <- system.time(vector_total <- sum(sqrt(values)))[["elapsed"]]
cat("results equal:", isTRUE(all.equal(loop_total, vector_total)), "\n")
cat("vectorized faster:", vector_time < loop_time, "\n")

On the test machine the loop took about 0.37 seconds and the vectorized version about 0.10 seconds, a speedup of roughly 3.7. The script prints only the equality check and the faster flag, so its output does not change between runs. The exact ratio depends on the machine and on the JIT compiler. The vectorized version avoids the R-level loop, although sqrt(values) creates a temporary vector; the trade-off is usually worthwhile for a vector of this size. The equality check uses all.equal because floating-point addition is not associative; the two sums can differ in the last bits.

$ Rscript vectorized.R
results equal: TRUE 
vectorized faster: TRUE 

Preallocation

Growing a vector with c(out, i) allocates a new vector and copies the old elements on every iteration, so the total copying work is quadratic. Preallocating the result and assigning by index reuses one vector. The next script compares the two methods for twenty thousand elements.

preallocate.R
grow <- function(n) {
  out <- numeric(0)
  for (i in 1:n) out <- c(out, i)
  out
}
preallocate <- function(n) {
  out <- numeric(n)
  for (i in 1:n) out[i] <- i
  out
}
n <- 20000
grow_time <- system.time(a <- grow(n))[["elapsed"]]
prealloc_time <- system.time(b <- preallocate(n))[["elapsed"]]
cat("results equal:", identical(a, b), "\n")
cat("preallocated faster:", prealloc_time < grow_time, "\n")

Both functions return the same vector, and the script confirms that preallocation was faster. On the test machine growing took about 0.3 seconds and preallocation about 0.003 seconds, roughly a hundred times less. The gap grows with n because the growing version copies 1 + 2 + ... + n elements. The preallocated version still runs an R loop, so it is not as fast as a vectorized expression, but it avoids the repeated allocation. The same rule applies to lists and data frames: create the container at its final size and fill it by position.

$ Rscript preallocate.R
results equal: TRUE 
preallocated faster: TRUE 

Profiling with Rprof

A profiler samples the call stack at regular intervals and records which function is running. Rprof writes those samples to a file; summaryRprof turns the file into tables of self time and total time. Self time counts only the samples where the function itself was on top of the stack; total time includes the functions it called. The next script profiles a function that fills a vector in a loop.

profiling.R
read_values <- function(n) {
  values <- numeric(n)
  for (i in seq_len(n)) {
    values[i] <- i
  }
  values
}
summarise <- function(x) {
  c(n = length(x), mean = mean(x))
}
work <- function(n) {
  values <- read_values(n)
  summarise(values)
}
Rprof("profile.out", interval = 0.01)
result <- work(2000000)
Rprof(NULL)
report <- summaryRprof("profile.out")
cat("n:", format(result[["n"]], scientific = FALSE), "mean:", format(result[["mean"]], scientific = FALSE), "\n")
cat("top function:", rownames(report$by.self)[1], "\n")

The profile file records samples every ten milliseconds while work runs. summaryRprof reports read_values as the function with the most self time, which is expected: the loop and the assignments are inside it, while summarise only calls length and mean. The report also has self.pct, total.time, and total.pct columns; the percentages vary with the sample count, but the function at the top of the self-time table is the place to optimize first. RStudio users can visualize the same samples with the profvis package, which draws an interactive flame graph from the profile data.

$ Rscript profiling.R
n: 2000000 mean: 1000000 
top function: "read_values" 

Byte compilation

R compiles functions to byte code before running them when JIT is enabled. The compiler is on by default in recent versions, so an explicit cmpfun often changes little. The next script turns JIT off, measures an interpreted function, compiles the same function with compiler::cmpfun, and measures it again. enableJIT returns the previous level, which is why the calls are wrapped in invisible.

byte-compile.R
invisible(compiler::enableJIT(0))
work <- function(n) {
  total <- 0
  for (i in 1:n) total <- total + i * 1.0
  total
}
compiled <- compiler::cmpfun(work)
cat("equal:", identical(work(1000), compiled(1000)), "\n")
interpreted_time <- system.time(work(1000000))[["elapsed"]]
compiled_time <- system.time(compiled(1000000))[["elapsed"]]
cat("compiled faster:", compiled_time < interpreted_time, "\n")
invisible(compiler::enableJIT(3))

Both versions return the same value, and the script confirms that the compiled version was faster. With JIT disabled, the interpreted loop took about 0.17 seconds and the compiled version about 0.02 seconds on the test machine. Byte code removes the repeated lookup of the loop body and the arithmetic operators. In ordinary sessions JIT is already on, so the gain from cmpfun is smaller; explicit compilation matters when JIT is unavailable or when a function is shipped in a package.

$ Rscript byte-compile.R
equal: TRUE 
compiled faster: TRUE 

Benchmarking with microbenchmark

A single system.time call includes noise from the operating system and from garbage collection. The microbenchmark package runs an expression many times and reports the minimum, lower quartile, mean, median, upper quartile, and maximum. The minimum is often the most stable summary because it is least affected by interruptions. The package is not part of base R, so it must be installed and loaded.

bench.R
library(microbenchmark)
values <- as.numeric(seq_len(10000))
loop_sum <- function(x) {
  total <- 0
  for (i in seq_along(x)) total <- total + sqrt(x[i])
  total
}
results <- microbenchmark(
  loop = loop_sum(values),
  vector = sum(sqrt(values)),
  times = 50
)
summary_results <- summary(results)
cat("expressions:", paste(as.character(summary_results$expr), collapse = ", "), "\n")
cat("fastest:", as.character(summary_results$expr[which.min(summary_results$median)]), "\n")

The summary has one row per expression and columns for the minimum, lower quartile, mean, median, upper quartile, and maximum, plus the number of evaluations. The script prints the expression names and the fastest one instead of the timings, so its output is stable. On the test machine the loop's median was about 335 microseconds and the vectorized call's median about 40 microseconds, roughly eight times faster. The max column is much larger than the median because the operating system can interrupt a run. Compare medians or minima, not single measurements.

$ Rscript bench.R
expressions: loop, vector 
fastest: vector 

A complete example: benchmarking three implementations

The final script compares a loop, a compiled loop, and a vectorized expression on the same vector. microbenchmark collects the samples, summary reduces them to one row per expression, and which.min picks the smallest median. The script prints only the equality check and the name of the fastest method, so the result is stable even though the times are not.

benchmark.R
library(microbenchmark)
n <- 100000
values <- as.numeric(seq_len(n))
loop_sum <- function(x) {
  total <- 0
  for (i in seq_along(x)) total <- total + x[i]^2
  total
}
vector_sum <- function(x) sum(x^2)
compiled_sum <- compiler::cmpfun(loop_sum)
results <- microbenchmark(
  loop = loop_sum(values),
  compiled = compiled_sum(values),
  vector = vector_sum(values),
  times = 30
)
summary_results <- summary(results)
cat("results equal:", isTRUE(all.equal(loop_sum(values), vector_sum(values))), "\n")
cat("fastest:", as.character(summary_results$expr[which.min(summary_results$median)]), "\n")

All three implementations return the same sum of squares. The vectorized expression is fastest because it avoids the R loop entirely; the compiled loop and the interpreted loop are both slower, and their order depends on the JIT settings. The ranking is the useful result. A benchmark that prints only times invites comparisons between machines; a benchmark that prints the winner and the equality check answers the question the code actually asks.

$ Rscript benchmark.R
results equal: TRUE 
fastest: vector 

Next steps

The vectorization article explains recycling and the functions that operate on whole vectors, and the apply family article shows the loops that lapply and vapply implement in C. The environments article explains why copying an environment is cheap, and the recursion article shows why deep recursion costs memory. The parallel article moves from making one core faster to using several cores.

Source

R manual: proc.time

R manual: system.time

R manual: Rprof

R manual: compile and cmpfun

CRAN: microbenchmark

Advanced R: Measuring performance

In this article we measured a call with proc.time and system.time, replaced an R loop with a vectorized expression, and preallocated a result instead of growing it one element at a time. We profiled a function with Rprof, read the self-time table, and compiled a function with compiler::cmpfun to see the difference in a session with JIT disabled. microbenchmark supplied repeated samples, and the final script reduced them to a ranking that does not depend on absolute times. The vectorization article explains the style that produces most of these gains, and the apply family article shows the C-level loops behind lapply and friends.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.