Home » Uncategorized

Loop-Runtime Comparison R, RCPP, Python

The positive reactions on my last post: “Different kinds of loops in R” lead me to compare some different versions of loops in R, RCPP (C++ integration of R). To see a bigger picture, I apply the Python for-loop additionally. The comparison focuses on the runtime for non-costly tasks with different numbers of iterations. For comparison purpose I create vectors in the form of (R syntax):

Vector <- 1:k

k = (1.000, 100.000, 1.000.000)

The task is to calculate a vector of (k-1) growth rates. I use a i7 8700k with 6 cores divided in two virtual cores each with Windows 10, 16 GB GDDR5.

I use the R-native for-loop, the sapply-loop, but also the parSapply-loop and RCPP like explained in “Different kinds of loops in R”. Additionally, I add the purrr::map() and the furrr::future_map functions.

The “purrr” package provides very flexible functional map() orders which can be used as loops. The “furrr” package is similar. It provides the same orders but with the option to use them in parallel.

For parallel use, you must change the default plan(sequential) to plan(multisession) in advance.

For comparison I use the mean of the elapsed time of 100 repetitions.

So, let´s check the results:

Note that the runtime is highly dependent from the complexity of each iteration. Therefore, the results merely count for this application or comparable applications. For a higher complexity I recommend parallel computing or C++.

3500615824

C++ is the clear winner. For this task, the Python and the R for-loops are similar. The functional solutions – in particular the parallel applications – are better for more complex computations. The parallel solutions use more memory because they assign one R-session to one thread.

Leave a Reply

Your email address will not be published. Required fields are marked *