Measuring execution time in R

Measuring execution time in R

Sometimes it is crucial to know how long it takes for your algorithm to run. Thus, you can make adjustments and optimize your algorithm to run efficiently simplifying chunks of code that take excessive time to run. In the next lines we will demonstrate two simple ways to measure time to execute.

First method

The run time of a chunk of code can be measured by taking the difference between the time at the start and at the end of the code chunk:

> start_time <- Sys.time() 
> for (i in seq(100000)) x[i] <- x[i]+1 
> end_time <- Sys.time() 
> #calculating difference in time
> end_time - start_time

# Time difference of 0.153 mins

Second method

The second way is equally simple with the first method.

> system.time({
>     #Do something the loop
>     x <- 1:100000 >    for (i in seq_along(x))  x[i] <- x[i]+1 >})
#    user  system elapsed 
#   0.144   0.002   0.153
No Comments

Sorry, the comment form is closed at this time.

× How can we help you?