Fast conversion from string time to milliseconds

For a vector or list of times, I would like to switch from string time, for example. 12:34:56.789 to the millisecond from midnight, which will be equal to 45296789 .

Here is what I am doing now:

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

and would like to do it faster.

Here is an example dataset for comparison:

 times = rep('12:34:56.789', 1e6) system.time(toms(times)) # user system elapsed # 9.00 0.04 9.05 
+6
source share
1 answer

You can use the fast time package, which seems to be about an order of magnitude faster.

 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 
+5
source

Source: https://habr.com/ru/post/952247/


All Articles