tags:

views:

59

answers:

3

What would be a good way to create a timer in R. One that would require little system resources.

So far I have a simple delay:

t1=as.numeric(format(Sys.time(), "%s"));
t2=t1; 
while (t2-t1<5) t2=as.numeric(format(Sys.time(), "%s"));

And the corresponding timer:

t1=as.numeric(format(Sys.time(), "%s"));t2=t1;

[Event]

t2=as.numeric(format(Sys.time(), "%s"));
time=t2-t1;

Thanks for reading.

+2  A: 

For starters, drop the as.numeric(format()) business -- not doing it saves you 'system resources' and you can compute on date / time types anyway. The rest of your code can remain as is.

Otherwise, a timer would commonly run in its own event loop. Given that R is single-threaded this is tricky but if I recall folks have done it, e.g. with the tcltk package included with R.

Dirk Eddelbuettel
+3  A: 

If you just want to have R pause and not take up resources for a given amount of time then use the Sys.sleep function.

If you want something more sophisticated where you can have R doing other things or other interactions, but have something happen after a given delay then it will be better to go the tcltk route.

Greg Snow
+1  A: 

Did you just want the runtime for an expression? Then you can use system.time, eg,

system.time(sum(1:1e5))

I'm a newbie with the tcltk package, but I wonder if Dirk and Greg were talking about something like the following:

after <- function(ms, func) {
  library(tcltk)
  invisible(.Tcl(paste("after", ms, .Tcl.callback(func))))
}

Example:

> after(7000, function() cat("hi!\n"))
> cat("hello?\n")
hello?
hi!

The docs from Revolution Analytics were helpful: http://www.inside-r.org/r-doc/tcltk/tclRequire Description of the Tcl "after" command: http://www.astro.princeton.edu/~rhl/Tcl-Tk_docs/tcl/after.n.html

David F