rtimingnamedsystemtime

How can I extract the numeric value from the time difference generated by Sys.time() in R?


t1 <- Sys.time()
mean((rnorm(10000))^2)
t2 <- Sys.time() 
print(t2-t1)
print(" ")

t1 <- Sys.time()
mean((rnorm(10000))^2)
t2 <- Sys.time() 
print(difftime(t2, t1, units = "secs")[[1]])

I want to compare the time efficiency of a few algorithms for computing the same target, so I tried the two ways above to extract the time difference computed by Sys.time(). However, neither gives a clear numeric.

[1] 0.9998752
Time difference of 0.03889418 secs
[1] " "
[1] 0.9832738
[1] 0.05183697

I also tried proc.time(). It would be great to extract the 3 numeric values into a vector, but none of as.numeric(t), t[0], t['user'], and t[['user']] works. Those are some relevant solutions I found online. How can I get one (or three, either is fine) neat figure from the timing result?

t1 <- proc.time()
mean((rnorm(10000))^2)
t2 <- proc.time() 
t <- t2 - t1
print(" ")
print(t)


[1] " "
   user  system elapsed 
   0.00    0.02    0.17 

Is there an equivalent way in R to do what the code below does in Python?

import numpy as np
from time import process_time

t = process_time()
np.mean(np.random.normal(loc=0,scale=1,size=10000))
t = process_time() - t
print(t)

Solution

  • You could use system.time():

    system.time({mean((rnorm(1e7))^2)})
    
           user      system       total 
           0.65        0.00        0.67 
    

    or package tictoc:

    library(tictoc)
    tic()
    mean((rnorm(1e7))^2)
    #> [1] 0.9998728
    toc()
    #> 0.66 sec elapsed
    

    For better precision, another alternative is microbenchmark which allows to compare different implementations by running them many times :

    microbenchmark::microbenchmark( 
      solution_A ={mean((rnorm(1e4))^2)},
      solution_B ={
        mysum <- 0
        for (i in 1:1e4) {
          mysum <- mysum + rnorm(1)^2
        }
        mysum / 1e4
      }
    )
    
    Unit: microseconds
           expr     min       lq      mean   median      uq      max neval cld
     solution_A   557.4   570.20   595.785   589.65   597.5   1161.0   100  a 
     solution_B 16177.3 16918.95 22115.115 17347.85 19315.5 247916.7   100   b
    

    for more details, see this link.