So far, we have seen how to measure the execution time of a whole R expression. What about a more complex expression with multiple parts such as calls to other functions? Is there a way to dig deeper and profile the execution time of each of the parts that make up the expression? R comes with the profiling tool Rprof()
that allows us to do just that. Let's see how it works.
In this example, we write the following sampvar()
function to calculate the unbiased sample variance of a numeric vector. This is obviously not the best way to write this function (in fact R provides the var()
function to do this), but it serves to illustrate how code profiling works:
# Compute sample variance of numeric vector x sampvar <- function(x) { # Compute sum of vector x my.sum <- function(x) { sum <- 0 for (i in x) { sum <- sum + i } sum } # Compute sum of squared variances...