【问题标题】:get execution time in milliseconds in R在 R 中以毫秒为单位获取执行时间
【发布时间】:2011-11-24 16:57:12
【问题描述】:

我已经阅读了使用tic(), toc() functions 的解决方案

tic <- function(gcFirst = TRUE, type=c("elapsed", "user.self", "sys.self"))
{
   type <- match.arg(type)
   assign(".type", type, envir=baseenv())
   if(gcFirst) gc(FALSE)
   tic <- proc.time()[type]         
   assign(".tic", tic, envir=baseenv())
   invisible(tic)
}

toc <- function()
{
   type <- get(".type", envir=baseenv())
   toc <- proc.time()[type]
   tic <- get(".tic", envir=baseenv())
   print(toc - tic)
   invisible(toc)
}




tic();
-----code----
toc();


elapsed 
   0.15 

但我想以毫秒为单位获得很多精度?

我也在用这个

ptm <- proc.time()
---code
proc.time() - ptm

得到这个

   user  system elapsed 
   1.55    0.25    1.84 

如何获得更多小数或更精确?

【问题讨论】:

  • 来自proc.time 的帮助页面:“时间分辨率将因系统而异,在 Unix-likes 上,时间四舍五入到最接近的 1 毫秒。”

标签: r benchmarking execution-time milliseconds


【解决方案1】:

1) 时间取决于操作系统。在 Windows 上,您可能只需要几毫秒。

2) 无需定义tic() 和toc(),R 有system.time()。这是一个例子:

R> system.time(replicate(100, sqrt(seq(1.0, 1.0e6))))
   user  system elapsed 
  2.210   0.650   2.867 
R> 

3) 有出色的附加包rbenchmark 和microbenchmark。

3.1)rbenchmark对命令比较特别有用,但也可以直接使用:

R> library(rbenchmark)
R> x <- seq(1.0, 1.0e6); benchmark(sqrt(x), log(x))
     test replications elapsed relative user.self sys.self user.child sys.child
2  log(x)          100   5.408  2.85835      5.21     0.19          0         0
1 sqrt(x)          100   1.892  1.00000      1.62     0.26          0         0
R>

3.2) microbenchmark 擅长最高精度测量:

R> library(microbenchmark)
R> x <- seq(1.0, 1.0e6); microbenchmark(sqrt(x), log(x))
Unit: nanoseconds
     expr      min       lq   median       uq      max
1  log(x) 50589289 50703132 55283301 55353594 55917216
2 sqrt(x) 15309426 15412135 15452990 20011418 39551819
R> 

最后一个,尤其是在 Linux 上,已经为您提供了纳秒级。它还可以绘制结果等,因此请仔细查看该包。

【讨论】:

  • 如果我有不止一行代码要测量,我将如何使用system.time(replicate(1000, ----several lines of code------ ))?
【解决方案2】:

这个不错:

options(digits.secs = 6) # This is set so that milliseconds are displayed

start.time <- Sys.time()

...Relevant code...

end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken

取自here。

【讨论】:

  • 这不会提供精确到毫秒的执行时间。答案只是另一个答案的副本,只是该答案更适合该问题。
  • 嗯...奇怪 :) 我只是为自己的代码计时,结果是:“时间差为 1.47222 秒”现在我很好奇您认为毫秒是多少?
  • 您需要设置 options(digits.secs=6) 才能看到 Sys.time() 确实包含毫秒数据。如果没有,它只会显示二级数据,这会让人们误以为这没有毫秒信息。
【解决方案3】:

将start_time 放在您的代码之前,将end_time 放在您的代码之后。

即

start_time <- as.numeric(as.numeric(Sys.time())*1000, digits=15) # place at start

-----code----

end_time <- as.numeric(as.numeric(Sys.time())*1000, digits=15) # place at end

end_time - start_time    # run time (in milliseconds)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 2017-08-05
    • 2013-05-09
    相关资源
    最近更新 更多