Computational Statistics

Chapter 15 - Programming Topics

Dr. Mehdi Maadooliat

Marquette University
MATH 4750 - Spring 2025

Programming Topics in R

Benchmarking Methods

  • Overview of benchmarking in R
  • Example: Benchmarking methods to generate a sequence
s1 <- 1:10
s2 <- seq(1, 10, 1)
s3 <- seq.int(1, 10, 1)

# Benchmarking
library(microbenchmark)
library(ggplot2)

n <- 1000
mb <- microbenchmark(
  seq(1, n, 1),
  1:n,
  times = 100
)
mb
Unit: nanoseconds
         expr   min      lq     mean median    uq   max neval
 seq(1, n, 1) 16971 17798.5 19162.03  18474 18785 57627   100
          1:n   100   120.0   187.54    180   211  1162   100
autoplot(mb)

Profiling Code for Performance

  • Introduction to profiling in R
  • Example: Profiling a function using profvis
# Install profvis for profiling
library(profvis)

# Example: Profile a sorting function
profvis({
  x <- rnorm(1e4)
  y <- sort(x)
})

Visualizing Profiling Results

# profvis visual interface will show the profiling output

Conclusion

  • Recap of benchmarking and profiling in R
  • Practice: Apply these techniques to optimize code in R