BaşlayınÜcretsiz Başlayın

Benchmarking with microbenchmark

Because the main motivation for Rcpp is performance, you need to be able to accurately measure how long your code takes to run. You will use the microbenchmark() function from the microbenchmark package for this purpose.

microbenchmark() takes named expressions as arguments, executes each expression a given number of times (100 by default) in a random order, and returns some summary statistics. In this course, we only care about the median column.

A vector x consisting of 100,000 standard normal random numbers is available in your workspace.

Bu egzersiz

Optimizing R Code with Rcpp

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

  • Load the microbenchmark package.
  • Write a function sum_loop() that calculates the sum of all the elements in a vector using an R for loop .
  • Verify that you get the same result with the sum() function using the all.equal() function.
  • Compare the performance with microbenchmark().

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

# Load microbenchmark
___

# Define the function sum_loop
sum_loop <- function(x) {
  result <- 0
  ___
  result
}

# Check for equality 
___(sum_loop(x), sum(x))

# Compare the performance
___(sum_loop = sum_loop(x), R_sum = sum(x))
Kodu Düzenle ve Çalıştır