dns*_*dns 263 time profiling r
测量执行时间的R是否有标准化的方法?
显然我可以system.time
在执行之前和之后采取,然后采取其中的差异,但我想知道是否有一些标准化的方式或功能(想要不发明轮子).
我似乎记得我曾经使用过如下的东西:
somesysfunction("myfunction(with,arguments)")
> Start time : 2001-01-01 00:00:00 # output of somesysfunction
> "Result" "of" "myfunction" # output of myfunction
> End time : 2001-01-01 00:00:10 # output of somesysfunction
> Total Execution time : 10 seconds # output of somesysfunction
Run Code Online (Sandbox Code Playgroud)
Shr*_*yes 234
另一种可能的方法是使用Sys.time():
start.time <- Sys.time()
...Relevent codes...
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken
Run Code Online (Sandbox Code Playgroud)
与上面的回答相比,这不是最优雅的方式,但绝对是一种方法.
And*_*rie 175
内置函数system.time()
将执行此操作.
使用如下: system.time(result <- myfunction(with, arguments))
Sac*_*amp 56
正如安德里所说,system.time()
工作正常.对于简短的功能,我更喜欢放入replicate()
它:
system.time( replicate(10000, myfunction(with,arguments) ) )
Run Code Online (Sandbox Code Playgroud)
csg*_*pie 37
测量执行时间的一种更好的方法是使用rbenchmark软件包.这个包(轻松)允许您指定复制测试的次数,相对基准应该是多少.
另请参阅stats.stackexchange中的相关问题
Rod*_*dre 32
还有 proc.time()
你可以使用相同的方式,Sys.time
但它会给你一个类似的结果system.time
.
ptm <- proc.time()
#your function here
proc.time() - ptm
Run Code Online (Sandbox Code Playgroud)
使用的主要区别
system.time({ #your function here })
Run Code Online (Sandbox Code Playgroud)
是这个proc.time()
方法仍然执行你的功能,而不仅仅是测量时间......顺便说一句,我喜欢在里面使用system.time
,{}
所以你可以放一套东西......
Dav*_*vic 27
microbenchmark
是一个轻量级(~50kB)的包,在R中或多或少是标准方式,用于对多个表达式和函数进行基准测试:
microbenchmark(myfunction(with,arguments))
Run Code Online (Sandbox Code Playgroud)
例如:
> microbenchmark::microbenchmark(log10(5), log(5)/log(10), times = 10000)
Unit: nanoseconds
expr min lq mean median uq max neval cld
log10(5) 0 0 25.5738 0 1 10265 10000 a
log(5)/log(10) 0 0 28.1838 0 1 10265 10000
Run Code Online (Sandbox Code Playgroud)
这两个表达式都被评估了10000次,平均执行时间约为25-30 ns.
Ant*_*ton 24
"tictoc"软件包为您提供了一种非常简单的测量执行时间的方法.文档位于:https://cran.fhcrc.org/web/packages/tictoc/tictoc.pdf.
install.packages("tictoc")
require(tictoc)
tic()
rnorm(1000,0,1)
toc()
Run Code Online (Sandbox Code Playgroud)
要将经过的时间保存到变量中,您可以执行以下操作:
install.packages("tictoc")
require(tictoc)
tic()
rnorm(1000,0,1)
exectime <- toc()
exectime <- exectime$toc - exectime$tic
Run Code Online (Sandbox Code Playgroud)
TPA*_*row 15
虽然其他解决方案对单个函数很有用,但我推荐以下一段更通用和有效的代码:
Rprof ( tf <- "log.log", memory.profiling = TRUE )
your code must be in between
Rprof ( NULL ) ; print ( summaryRprof ( tf ) )
Run Code Online (Sandbox Code Playgroud)
小智 11
另一个简单但非常强大的方法是使用该包profvis
.它不仅可以测量代码的执行时间,还可以深入了解您执行的每个函数.它也可以用于Shiny.
library(profvis)
profvis({
#your code here
})
Run Code Online (Sandbox Code Playgroud)
点击这里查看一些例子.
小智 8
您可以使用Sys.time()
。但是,当您在表或 csv 文件中记录时差时,不能简单地说end - start
。相反,您应该定义单位:
f_name <- function (args*){
start <- Sys.time()
""" You codes here """
end <- Sys.time()
total_time <- as.numeric (end - start, units = "mins") # or secs ...
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以使用total_time
它具有正确的格式。