Code optimization, an Rcpp solution

[This article was first published on Romain Francois, Professional R Enthusiast - Tag - R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Tony Breyal woke up an old code optimization problem in this blog post, so I figured it was time for an Rcpp based solution

This solutions moves down Henrik Bengtsson’s idea (which was at the basis of attempt 10) down to C++. The idea was to call sprintf less than the other solutions to generate the strings “001”, “002”, “003”, …

We can benchmark this version using the rbenchmark package:

> library(rbenchmark)
> n <- 2000
> benchmark(
+     generateIndex10(n), 
+     generateIndex11(n),
+     generateIndex12(n), 
+     generateIndex13(n),
+     generateIndex14(n),
+     columns = 
+        c("test", "replications", "elapsed", "relative"),
+     order = "relative",
+     replications = 20
+ )
                test replications elapsed relative
5 generateIndex14(n)           20  21.015 1.000000
3 generateIndex12(n)           20  22.034 1.048489
4 generateIndex13(n)           20  23.436 1.115203
2 generateIndex11(n)           20  23.829 1.133904
1 generateIndex10(n)           20  30.580 1.455151
>    

To leave a comment for the author, please follow the link and comment on their blog: Romain Francois, Professional R Enthusiast - Tag - R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)