如何在R中重新缩放时间差?
我经常想计算一个算法可能需要多长时间才能完成。我用如何在R中重新缩放时间差?,r,time,R,Time,我经常想计算一个算法可能需要多长时间才能完成。我用.Sys.time()拍摄开始时间的快照,并在完成部分任务(重复)后拍摄时间戳。然后,我通过除以已完成的任务,再乘以剩余的任务来扩大这个范围。但是,时间变量的单位不变。例如,如果以秒为单位,即使乘以任何标量,它仍将保持在该单位中。这导致两个问题: 乘以的数字仍以原始差值为单位,可能太大而无法解释(例如秒) 重新调整数字比例(例如除以60)后,时间变量的比例不变(例如,仍然指示秒) 我想在重新缩放到所需的任何时间测量值(秒、分钟、小时、天)后更改s
.Sys.time()
拍摄开始时间的快照,并在完成部分任务(重复)后拍摄时间戳。然后,我通过除以已完成的任务,再乘以剩余的任务来扩大这个范围。但是,时间变量的单位不变。例如,如果以秒为单位,即使乘以任何标量,它仍将保持在该单位中。这导致两个问题:
set.seed(12345)
j=0
s = Sys.time()
while(i == 0){
i = sample(x=c(0,1),size=1,replace=TRUE,prob=c(1-10^-6,10^-6) )
j = j+1
}
e = Sys.time()
dif = (e-s)
> dif
Time difference of 0.04200912 secs
现在假设任务必须执行另一次10E5
> dif*10^5
Time difference of 4200.912 secs
它仍然是原始比例的单位。现在如何将dif
转换为分钟或小时?以下内容具有误导性
> dif*10^5/60
Time difference of 70.01519 secs
使用
difftime
获取时差,因为它允许您指定单位。仅仅减去两次可能并不总能得到相同单位的差值。比较这两种情况
a = structure(1506077762.63353, tzone = "UTC", class = c("POSIXct", "POSIXt"))
b = structure(1505577762.63353, tzone = "UTC", class = c("POSIXct", "POSIXt"))
a - b
#Time difference of 5.787037 days
x = structure(1506078155.6917, tzone = "UTC", class = c("POSIXct", "POSIXt"))
y = structure(1506077155.6917, tzone = "UTC", class = c("POSIXct", "POSIXt"))
x - y
#Time difference of 16.66667 mins
至于重新缩放,您可以使用lubridate
软件包的seconds\u to\u period
功能
#DATA
s = Sys.time()
Sys.sleep(4)
e = Sys.time()
dif = difftime(time1 = e, time2 = s, units = "secs")
dif
#Time difference of 4.045822 secs
library(lubridate)
seconds_to_period(round(dif*1e5, 0))
#[1] "4d 16H 23M 2S"
或者您也可以使用基本R的difftime
difftime(time1= as.POSIXct(as.numeric(dif*1e5), origin = "1970-01-01 00:00:00", tz = "UTC"),
time2= as.POSIXct("1970-01-01 00:00:00", tz = "UTC"),
units= "hours")
#Time difference of 112.3839 hours
使用
difftime
获取时差,因为它允许您指定单位。仅仅减去两次可能并不总能得到相同单位的差值。比较这两种情况
a = structure(1506077762.63353, tzone = "UTC", class = c("POSIXct", "POSIXt"))
b = structure(1505577762.63353, tzone = "UTC", class = c("POSIXct", "POSIXt"))
a - b
#Time difference of 5.787037 days
x = structure(1506078155.6917, tzone = "UTC", class = c("POSIXct", "POSIXt"))
y = structure(1506077155.6917, tzone = "UTC", class = c("POSIXct", "POSIXt"))
x - y
#Time difference of 16.66667 mins
至于重新缩放,您可以使用lubridate
软件包的seconds\u to\u period
功能
#DATA
s = Sys.time()
Sys.sleep(4)
e = Sys.time()
dif = difftime(time1 = e, time2 = s, units = "secs")
dif
#Time difference of 4.045822 secs
library(lubridate)
seconds_to_period(round(dif*1e5, 0))
#[1] "4d 16H 23M 2S"
或者您也可以使用基本R的difftime
difftime(time1= as.POSIXct(as.numeric(dif*1e5), origin = "1970-01-01 00:00:00", tz = "UTC"),
time2= as.POSIXct("1970-01-01 00:00:00", tz = "UTC"),
units= "hours")
#Time difference of 112.3839 hours
查看
?difftime
查看?difftime
谢谢,秒到秒周期
非常有用。唯一奇怪的是秒的数字太多了。太好了,这正是我想要的。谢谢,seconds\u to\u period
非常有用。唯一奇怪的是秒数相当高。太好了,这正是我想要的。