2013-08-21 36 views
6

对于一个向量或时间列表,我希望从字符串时间开始,例如, 12:34:56.789从午夜到毫秒,这将等于45296789从字符串时间快速转换为毫秒

这就是我现在做的事:

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

,想做得更快。

下面是一个示例数据为基准设置:

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

system.time(toms(times)) 
# user system elapsed 
# 9.00 0.04 9.05 

回答

5

你可以使用fasttime包,这似乎是约一个数量级快。

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