本文介绍了以R为单位获取执行时间(以毫秒为单位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了使用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

但是我想获得毫秒级的精度吗?

But I would like to get a lot of precision in milliseconds?

我也正在使用

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

并获得

   user  system elapsed
   1.55    0.25    1.84

如何获取更多的小数位数或更高的精度?

How to get more decimals or more precision?

推荐答案

1)时间取决于操作系统.在Windows上,您可能只会获得毫秒.

1) Timing is operating-system dependent. On Windows you may only get milliseconds.

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

2) No need to define tic() and toc(), R has system.time(). Here is an example:

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) There are excellent add-on packages rbenchmark and microbenchmark.

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

3.1) rbenchmark is particularly useful for comparison of commands, but can also be used directly:

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 在最高精度的测量中表现出色:

3.2) microbenchmark excels at highest precision measurements:

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上,已经为您提供了纳秒级的时间.它还可以绘制结果等,因此请仔细查看该程序包.

and this last one, particularly on Linux, already gives you nano-seconds. It can also plot results etc so have a closer look at that package.

这篇关于以R为单位获取执行时间(以毫秒为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-10 05:31