【问题标题】:How can I extract the numeric value from the time difference generated by Sys.time() in R?如何从 R 中 Sys.time() 生成的时间差中提取数值?
【发布时间】:2020-09-22 21:04:16
【问题描述】:
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']] 都不起作用。这些是我在网上找到的一些相关解决方案。如何从计时结果中得到一个(或三个都可以)整齐的数字?

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)

【问题讨论】:

  • as.numeric 有一个 difftime 对象的方法 - as.numeric(t2 - t1, units="secs")。指定你想要的单位然后离开!
  • @thelatemail 也许我没明白你的意思。我试过as.numeric(t2-t1, units='secs')as.numeric(difftime(t2, t1, units='secs')),都没有得到一个整洁的数字。
  • 对我有用 Sys.time 结果 - t1 &lt;- Sys.time(); Sys.sleep(3); t2 &lt;- Sys.time(); as.numeric(t2 - t1, units="secs")
  • @thelatemail 谢谢,但恐怕它对我不起作用。它输出两个未命名的数字:[1] 0.9842054 [1] 0.04188514
  • 鉴于我提供的代码,这些数字实际上是不可能的,因为我在计算 t1t2 之间强制等待 3 秒。

标签: r timing named systemtime


【解决方案1】:

你可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 2019-05-18
    • 2021-07-18
    相关资源
    最近更新 更多