Time formatting: how to write a While loop that operates for a whole minute?

北城以北 提交于 2021-02-11 14:40:50

问题


I have written the following function:

iterations_per_minute = function() {
    Sys.setenv(TZ='GMT+5')        ## This line is optional; it just sets my timezone   
    final_instant = as.numeric(format(Sys.time(), "%H.%M")) + 0.01
    counter = 0

    while(as.numeric(format(Sys.time(), "%H.%M")) < final_instant) {
      counter = counter + 1
    }

    return(counter)
}

You can infer from the code what the function does, but allow me to explain in lay words anyway: what number can you reach by counting as fast as possible during one minute starting from the number 1? Think of the computer doing exactly that same thing. The output of this function is the number that the computer reaches after counting for a whole minute.

Or at least that is how I would like this function to behave. It does work the way I have described if we pair exactly the call to the function with the beginning of a minute in the clock. However, it will count for less than a minute if we execute this function when the second hand of the clock is pointing at any other number besides twelve. How do I fix this?

Also, I figure I probably won't get the desired output if I execute the function between 23:59 and 0:00. How can this other issue be fixed?


回答1:


Seems to me like you're trying to introduce more moving parts than you need. Consider the following:

a <- Sys.time()
a
# [1] "2020-07-25 16:21:40 CDT"
a + 60
# [1] "2020-07-25 16:22:40 CDT"

So, we can just add 60 to Sys.time() without worrying about conversions or whatever else:

iterations_per_minute = function() {
    counter = 0
    end <- Sys.time() + 60
    while( Sys.time() < end )  {
        counter = counter + 1
    }
    return(counter)
}

Using this function, apparently my machine can count to 1474572 in one minute.



来源:https://stackoverflow.com/questions/63093569/time-formatting-how-to-write-a-while-loop-that-operates-for-a-whole-minute

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