时间格式:如何编写一个可以运行一分钟的While循环? [英] Time formatting: how to write a While loop that operates for a whole minute?

查看:76
本文介绍了时间格式:如何编写一个可以运行一分钟的While循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下函数:

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

您可以从代码中推断出函数的作用,但是无论如何我还是要用一个简单的词来解释:从数字1开始的一分钟内尽可能快地计数,您可以得出哪个数字?想一想计算机做的完全一样的事情.此功能的输出是计算机计数一整分钟后到达的数字.

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?

此外,我认为如果我在23:59到0:00之间执行该功能,可能不会得到所需的输出.如何解决其他问题?

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?

推荐答案

在我看来,您正在尝试引入比您需要的更多运动部件.请考虑以下内容:

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"

因此,我们只需在 Sys.time()中添加60,而不必担心转换或其他任何问题:

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

使用此功能,显然我的机器在一分钟内就可以计数到1474572.

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

这篇关于时间格式:如何编写一个可以运行一分钟的While循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆