如何从 R 中 Sys.time() 生成的时差中提取数值?

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]])

我想比较几种算法计算同一个目标的时间效率,所以我尝试了上面的两种方法来提取Sys.time()计算的时间差。但是,都没有给出明确的数字。

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

我也试过proc.time()。将 3 个数值提取到一个向量中会很棒,但是 as.numeric(t)t[0]t['user']t[['user']] 中的 none 有效。这些是我在网上找到的一些相关解决方案。如何从计时结果中得到一个(或三个,都可以)整齐的数字?

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 

R 中是否有等效的方法来完成下面代码在 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)

您可以使用 system.time():

system.time({mean((rnorm(1e7))^2)})

       user      system       total 
       0.65        0.00        0.67 

或包裹tictoc:

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

为了获得更好的精度,另一种选择是 microbenchmark,它允许通过 运行 多次比较不同的实现:

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

有关详细信息,请参阅此 link