r - 获取 R 中的执行时间(以毫秒为单位)

标签 r benchmarking execution-time milliseconds

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

如何获得更多的小数点或更高的精度?

最佳答案

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)有优秀的附加包rbenchmarkmicrobenchmark

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

关于r - 获取 R 中的执行时间(以毫秒为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7546946/

相关文章:

r - 如何使用 dplyr 的 coalesce 函数和 group_by() 为每个人创建一行并填充所有值?

r - 使用 sourceCpp() 的 Rcpp 和 RcppArmadillo 在 R 中出错

PHP检查字符串是否为UTF-8的最快方法?

python - PyPy 比 Python 快 17 倍。 Python可以加速吗?

r - R 中的编码实践 : what are the advantages and disadvantages of different styles?

R Shapefile 未正确绘制纬度/经度

testing - 如何一次对 Redis 的所有操作进行基准测试

c++ - 为什么两个几乎相同的实现有很大的执行时间差异?

java - 在 Virtuoso 服务上使用 Jena 的 SPARQL 查询执行时间

algorithm - 算法分析——三个嵌套依赖循环的时间复杂度