[R] get time as a number

Gabor Grothendieck ggrothendieck at gmail.com
Sun Sep 19 15:52:33 CEST 2010


On Sun, Sep 19, 2010 at 9:19 AM, Hyunchul Kim
<hyunchul.kim.sfc at gmail.com> wrote:
> Hi, all,
>
> How to get a time as a number?
>
> While script is running, I want to print the elapsed time
>
> something like TIME_AS_SECOND() in the following script
>
> inittime <- TIME_AS_SECOND()
> for (i in 1:100){
>    do_something(i)
>    curtime <- TIME_AS_SECOND()
>    elapsedtime <- curtime-inittime
>    print(paste(i, elapsedtime))
> }
>

Here are a few things to try:

> # 1 - diff.POSIXt
> init.time <- Sys.time()
> x1 <- 0
> for (i in 1:100000) x1 <- x1 + 1
> Sys.time() - init.time
Time difference of 0.4130001 secs
>
> # 2 - converting to numeric
> init.time <- as.numeric(Sys.time())
> x2 <- 0
> for(i in 1:100000) x2 <- x2 + 1
> as.numeric(Sys.time()) - init.time
[1] 0.3270001
>
> # 3 - proc.time
> init.time <- proc.time()
> x3 <- 0
> for(i in 1:100000) x3 <- x3 + 1
> proc.time() - init.time
   user  system elapsed
   0.25    0.03    0.33
>
> # 4 - system.time
> system.time({ x4 <- 0; for(i in 1:100000) x4 <- x4 + 1 } )
   user  system elapsed
   0.19    0.02    0.23
>
> # 5 - rbenchmark package
> library(rbenchmark)
> benchmark(replications = 10,
+ x1 = {x5 <- 0; for(i in 1:100000) x5 <- x5 + 1 },
+ x2 = { x5. <- 0; for(i in 1:200000) x5. <- x5. + 1}
+ )
  test replications elapsed relative user.self sys.self user.child sys.child
1   x1           10    2.38 1.000000      1.95     0.06         NA        NA
2   x2           10    4.87 2.046218      3.84     0.08         NA        NA

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list