In this tutorial, we will learn how to measure execution time in R. We will learn two ways, using Sys.time() and system.time, of measuring execution time in R. Both the methods to measure running time are readily available in base R and do need use any outside R packages.
Measuring Execution Time with Sys.time()
We will first show how to use Sys,time() function in R to measure how long it takes to run a chunk of R code, for example a R function.
Sys.time() function gives us current date and time. Here is an example use of Sys.time().
Sys.time() [1] "2023-01-06 01:33:39 EST"
Sys.time returns an object of class “POSIXct” and. as per the document Sys.time will have sub-second accuracy (possibly microseconds or better) on all systems.
Our approach to use Sys.time() function to get the execution time or running time is to get the date and time before an after our code chunk or function. The difference between the two times is our estimation of the execution time of running R code.
In the example below, we use Sys.sleep() function as our code chunk of interest. Sys.sleep() function suspends execution of R expressions for a specified time interval. The argument to Sys.sleep() is how long we want to suspend execution of R. Here we use Sys.sleep() for 60 seconds and
# get the start time before running the code start <- Sys.time() Sys.sleep(60) # get the. time after running the code end <- Sys.time() print(start) print(end) ## [1] "2023-01-06 01:33:06 IST" ## [1] "2023-01-06 01:34:06 IST"
And from the. start and end time, we can get the total time it took to run our code is by computing the difference in time
end-start ## Time difference of 1.000516 mins
Measuring running time. with system.time() function
Another way to measuure the time taken. to run R code is to use system.time() function available in. R. systeem.time() function gives us “CPU Time Used”
Under the hood system.time() calls the function proc.time(), evaluates the argument, and then calls proc.time once more, returning the difference between the two proc.time calls. (just as we used Sys.time() in the previous example.
Here is an example using. system.time() to measure the Sys.sleep(60) as before.
system.time(Sys.sleep(60)) ## user system elapsed ## 0.000 0.001 60.002
system.time gives us three different times and the one that is relevant to us is “elapsed” time and it is slightly more than a minute as it includes some over head time.