Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to best create a Timer Function in R

I'm trying to create a function in R that returns for the first x seconds after the function call 1, the next x seconds 0, the next x seconds 1 again,...the whole procedure should stop after another time interval or after n iterations. I want to do this with one function call.

I read about the package tcltk which apparently entails some possibilities to create such "timer" functions, however I did not find enough explanations to sort out my issue.

Could you advise me where to find a good manual that explains tcl in context with R? Do you have other ideas how to create such a function in an efficient way?

Thanks a lot for your help.

like image 568
Eva Avatar asked Jan 31 '11 16:01

Eva


People also ask

How do I time a function in R?

We have to first install and import the library called “tictoc“. Then we define our sample function that runs for some specific duration. Call the tic() function, then place any R expression or code or function(), then end it with toc() function call. It will print the execution time of the sleep_func().

What is a timer function?

A timer is a specialized type of clock which is used to measure time intervals. A timer that counts from zero upwards for measuring time elapsed is often called a stopwatch. It is a device that counts down from a specified time interval and used to generate a time delay, for example, an hourglass is a timer.

How long does r take to run?

It takes 4-6 weeks to learn R without programming knowledge.


2 Answers

If I understood you correctly, you are trying to create a function that will return 1 whenever it is called in the first x secs, then return 0 whenever it's called in the next x secs, then return 1 over the next x secs, etc. And after a certain total time, it should be "done", maybe return -1?

You could do this using the following function that will "create" a function with any desired interval:

flipper <- function(interval=10, total = 60) {
  t0 <- Sys.time()
  function() {
    seconds <- round(as.double( difftime(Sys.time(), t0, u = 'secs')))
    if(seconds > total)
      return(-1) else
    return(trunc( 1 + (seconds / interval ) ) %% 2)
  }
}

You can use this to create a function that alternates between 0 and 1 every 10 secs during the first 60 seconds, and returns -1 after 60 seconds:

> flp <- flipper(10,60)

Now calling flp() will have the behavior you are looking for, i.e. when you call flp() during the next 60 secs, it will alternate between 1 and 0 every 10 secs, then after 60 secs it will just return -1.

like image 76
Prasad Chalasani Avatar answered Oct 02 '22 17:10

Prasad Chalasani


Sys.sleep from base could not be a solution?

E.g.: stop every 10th iteration in a loop for 10 seconds:

for (i in 1:100) {
    # do something
    if ((i %% 10) == 0) {
        Sys.sleep(10)
    }
}
like image 40
daroczig Avatar answered Oct 02 '22 17:10

daroczig