Benchmarking
Two understand the benefits of using C++ equivalent we’ll benchmark both functions sumTwoR and sumTwoC, using package microbenchmark. Install it using install.packages(“microbenchmark”).
R
library (Rcpp) library (microbenchmark) # Writing a code in C++ to calculate the sum of vector values cppFunction (' double sumTwoC (NumericVector x, NumericVector y) { int n = x.size (); double total = 0; for (int i = 0; i < n; ++i) { total += x[i] + y[i]; } return total; }') # R code to add two vectors sumTwoR <- function (x, y) { total <- 0 for (i in 1: length (x)) { total <- total + x[i] + y[i] } return (total) } # Benchmarking the two functions x <- runif (1e6) y <- runif (1e6) # Create a horizontal bar plot of the results benchmark <- microbenchmark ( sumTwoC (x, y), sumTwoR (x, y), times = 100) |
Unit: milliseconds
expr min lq mean median uq max neval
sumTwoC(x, y) 1.100829 1.142826 1.250264 1.185279 1.231635 2.252383 100
sumTwoR(x, y) 44.789824 46.995613 49.763670 48.157485 50.708915 73.723904 100
Here we can see that the minimum time taken by sumTwoC is 2.25 ms but sumTwoR takes 44.78 ms, it’s a huge difference.
Plotting the benchmark results
I’m using ggplot2 for plotting the benchmark results.
R
# Plotting the results library (ggplot2) ggplot (benchmark, aes (x = expr, y = time, fill = expr)) + geom_bar (stat = "identity" ) + theme_bw () + coord_flip () + theme (axis.text.x = element_text (angle = 45, hjust = 1), axis.text = element_text (face = "bold" )) + labs (x = "Function" , y = "Time (ms)" , title = "Benchmarking sumTwo and sumTwoR" ) # Save the plot ggsave ( "benchmark.png" , width = 10, height = 5, dpi = 100) |
Output
How to Converting a R code into C++ for Rcpp implementation
When dealing with performance issues in R code, there may be situations where R alone is not sufficiently fast. To rescue there is a powerful package in R Programming Language called Rcpp that allows for seamless integration of C++ code into R, providing significant performance improvements. Converting R code into C++ using Rcpp can enhance computational efficiency, especially for computationally intensive tasks. This guide will walk you through the process of converting R code into C++ using Rcpp.