get execution time in milliseconds in R

喜夏-厌秋 提交于 2019-11-27 20:07:01

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

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

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 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> 

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.

This one is good:

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

Taken from here.

Place start_time before your code and end_time after your code.

i.e.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!