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)
You could use
system.time():or package
tictoc:For better precision, another alternative is
microbenchmarkwhich allows to compare different implementations by running them many times :for more details, see this link.