Last active
June 14, 2023 18:42
-
-
Save MattSandy/07cad79d3e8fd0214fe419f08721f3cf to your computer and use it in GitHub Desktop.
Two ways of formatting time periods from numeric
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(microbenchmark) | |
long_way <- function(time_vector) { | |
return( | |
time_vector |> | |
lapply(function(x){ | |
(x |> | |
str_match_all("[0-9]{1}") |> | |
unlist() |> | |
rev())[1:4] |> | |
(\(time){ | |
time[is.na(time)] <- "0" | |
paste0(time[4],time[3],":",time[2],time[1]) | |
})() | |
}) |> unlist() | |
) | |
} | |
longest_way <- function(time_vector) { | |
return( | |
time_vector |> | |
lapply(function(x){ | |
time <- x |> | |
as.character() |> | |
strsplit("\\.*") |> | |
(\(time){ | |
time <- rev(time[[1]])[1:4] | |
})() | |
time[is.na(time)] <- 0 | |
paste0(time[4],time[3],":",time[2],time[1]) | |
}) |> unlist() | |
) | |
} | |
short_way <- function(time_vector) { | |
return( | |
time_vector |> | |
lapply(function(x){ | |
x |> str_pad(4, "left", "0") |> stringr::str_replace("(.{2})(.{2})", "\\1:\\2") | |
})|> unlist() | |
) | |
} | |
shorter_way <- function(time_vector) { | |
return( | |
time_vector |> | |
lapply(function(x){ | |
prefixed <- sprintf("%04d", x) | |
return( | |
paste0(substr(prefixed,1,2),":",substr(prefixed,3,4)) | |
) | |
})|> unlist() | |
) | |
} | |
mbm = microbenchmark( | |
long = long_way(1:2000), | |
longest = longest_way(1:2000), | |
short = short_way(1:2000), | |
shortest = shorter_way(1:2000), | |
times=50 | |
) | |
mbm | |
# Unit: milliseconds | |
# expr min lq mean median uq max neval | |
# long 48.74027 53.048229 58.81344 55.52145 63.67269 80.42932 50 | |
# longest 32.54070 34.525115 38.54215 36.34376 39.71092 54.13282 50 | |
# short 147.91870 162.895009 174.57177 176.11646 184.59249 207.07270 50 | |
# shortest 9.14919 9.854754 11.47535 11.06433 11.55994 24.03890 50 | |
plot(mbm) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment