【问题标题】:How do you extract the time unit when using difftime()?使用 difftime() 时如何提取时间单位?
【发布时间】:2019-06-11 04:25:31
【问题描述】:

我目前正在运行一个 for 循环代码,在每个循环结束时,我正在测量循环的持续时间并打印一条消息,告诉用户循环花费了多长时间。

获取我正在使用的持续时间

duration <- difftime(end_time, start_time) 

这就是我打印声明的方式

print(paste("Loop", i, "took", duration, "to run.")). 

问题是每个循环的持续时间可能从 30 秒到 1 小时不等。将持续时间放入粘贴中只会将其转换为没有单位的数字。

例如

print(paste("Loop", i, "took", duration, "to run.")). 
"Loop 5 took 10.5 to run"

我如何从 difftime() 中获取单位以便获得类似:“Loop 5 运行了 10.5 分钟。”

PS:有些人可能会建议通过在 difftime() 中声明“单位”参数来标准化持续时间,但我希望用户可以轻松理解持续时间,这就是我将单位设置为默认“自动”的原因。

【问题讨论】:

    标签: r time difftime


    【解决方案1】:

    duration调用units获取单位,通过子集duration得到数值:

    print(paste("Loop", i, "took", round(duration[[1]], 2),  units(duration), "to run."))
    

    这是一个例子:

    start_time <- Sys.time()
    
    # few seconds later
    end_time <- Sys.time()
    
    duration <- difftime(end_time, start_time)
    
    print(paste("Loop", 1, "took", round(duration[[1]], 2),  units(duration), "to run."))
    

    结果:

    [1] "Loop 1 took 6.97 secs to run."
    

    根据持续时间的范围,该单位将是自动的。请参阅以下示例:

    start_time <- Sys.time()
    
    # few days later
    end_time <- as.Date("2019-01-23")
    
    duration <- difftime(end_time, start_time)
    
    print(paste("Loop", 1, "took", round(duration[[1]], 2),  units(duration), "to run."))
    

    结果:

    > print(paste("Loop", 1, "took", round(duration[[1]], 2),  units(duration), "to run."))
    [1] "Loop 1 took 5.9 days to run."
    

    【讨论】:

      【解决方案2】:

      一种方法是从difftime 捕获输出,因为它正在使用capture.output

      start_time <- as.POSIXct('2019-01-01 02:34:00')
      end_time <- as.POSIXct('2019-01-01 03:14:00')
      
      paste("Loop 5 took", capture.output(difftime(end_time, start_time)), "to run.")
      #[1] "Loop 5 took Time difference of 40 mins to run."
      

      现在您可以更改输出以使其有意义,例如从输出中删除“时间差”

      sent <- capture.output(difftime(end_time, start_time))
      paste("Loop 5 took",sub("Time difference of ","", sent) , "to run.")
      #[1] "Loop 5 took 40 mins to run."
      

      另一个输入

      start_time <- as.POSIXct('2019-01-01 02:34:00')
      end_time <- as.POSIXct('2019-01-01 02:34:50')
      
      sent <- capture.output(difftime(end_time, start_time))
      paste("Loop 5 took",sub("Time difference of ","", sent) , "to run.")
      #[1] "Loop 5 took 50 secs to run."
      

      【讨论】:

        【解决方案3】:

        您应该可以通过units(duration) 获得。

        【讨论】:

          猜你喜欢
          • 2013-06-07
          • 2020-06-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-26
          • 2014-11-12
          • 1970-01-01
          相关资源
          最近更新 更多