从字符串时间到毫秒的快速转换

edd*_*ddi 6 string r

对于向量或时间列表,我想从字符串时间开始,例如12:34:56.789从午夜到毫秒,这将等于45296789.

这就是我现在所做的:

toms = function(time) {
  sapply(strsplit(time, ':', fixed = T),
         function(x) sum(as.numeric(x)*c(3600000,60000,1000)))
}
Run Code Online (Sandbox Code Playgroud)

并希望更快地完成.

以下是基准测试的示例数据集:

times = rep('12:34:56.789', 1e6)

system.time(toms(times))
#   user  system elapsed 
#   9.00    0.04    9.05
Run Code Online (Sandbox Code Playgroud)

Jos*_*ich 5

你可以使用快速包,这似乎要快一个数量级.

library(fasttime)
fasttoms <- function(time) {
  1000*unclass(fastPOSIXct(paste("1970-01-01",time)))
}
times <- rep('12:34:56.789', 1e6)
system.time(toms(times))
#   user  system elapsed 
#   6.61    0.03    6.68 
system.time(fasttoms(times))
#   user  system elapsed 
#   0.53    0.00    0.53
identical(fasttoms(times),toms(times))
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)