Measuring Execution Time of Function in R (Example Code)

 

In this tutorial, I’ll illustrate how to check the execution time of a function in R programming.

The tutorial will contain the following information:

Let’s just jump right in…

 

Example: Measuring Function Execution Time in R

In this example; I’ll test how long it takes to draw a random distribution with different sample sizes. Let’s specify the two different sample sizes first:

N1 <- 10^5                  # First sample size
N2 <- 10^8                  # Second sample size

Now, let’s assume that we want to measure how long it takes to draw a normally distributed random number of this sample size with the rnorm function. Then we need to save the time before and after the application of rnorm. We can do that with the Sys.time function as follows:

start1 <- Sys.time()        # Save starting time
x1 <- rnorm(N1)             # Apply rnorm function to N1
end1 <- Sys.time()          # Finishing time

After running the previous R code, the starting and finishing time of the random draw is stored in the data objects start1 and end1. We can now compute the time difference between these two time objects as follows:

time1 <- end1 - start1      # Time difference between start & end
time1                       # Print time difference to console
# Time difference of 0.007977009 secs

As you can see based on the output of the RStudio console, the runtime difference between the starting and finishing time is 0.007977009.

Now we could compare this with a larger sample size. So let’s apply the same code as before to our second sample size N2…

start2 <- Sys.time()        # Save starting time
x2 <- rnorm(N2)             # Apply rnorm function to N2
end2 <- Sys.time()          # Finishing time

…and then let’s compute the time difference:

time2 <- end2 - start2      # Time difference between start & end
time2                       # Print time difference to console
# Time difference of 6.413143 secs

As you can see, the time difference for the second sample size if 6.413143 seconds – Much larger compared to the first sample size!

Note: In this example, we measured the elapsed time after running the rnorm function. However, you could evaluate the execution time of whatever function or R syntax you want. You simply need to store the system time before and after the application of your syntax.

 

Video, Further Resources & Summary

Have a look at the following video of my YouTube channel. In the video, I’m explaining the R programming syntax of this tutorial.

 

 

Besides the video, you might read the related articles of this website.

 

In this article you learned how to measure running time and performance in R. If you have any additional questions or comments, please let me know in the comments section.

 



Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top