Profiling Code with Rprof and profvis
Identify which functions consume the most time in your scripts.
What Is Profiling?
Timing tells you how long code runs. Profiling tells you where the time is spent inside that code. R's profiler samples the call stack at regular intervals to build a statistical picture of which functions are expensive.
Two main tools: the built-in Rprof() and the interactive profvis package.
Starting and Stopping Rprof()
Rprof('output.prof', interval = 0.01) starts the profiler. It writes call-stack samples to a file every 10 ms. Run your slow code, then call Rprof(NULL) to stop recording.
The interval argument controls sampling frequency in seconds — smaller values give more resolution but larger output files.
# Pattern — do not run Rprof inside knitr/Quarto
# Rprof('my_profile.prof', interval = 0.01)
#
# slow_function <- function(n) {
# x <- numeric(n)
# for (i in seq_len(n)) x[i] <- sqrt(i)
# sum(x)
# }
# slow_function(500000)
#
# Rprof(NULL) # stop profilingAll lessons in this course
- system.time() and proc.time()
- Profiling Code with Rprof and profvis
- Vectorization for Speed
- Benchmarking with microbenchmark