timer | R Documentation |
The 'timer' function allows you to append timeStamps to a data.table, and include additional metadata provided as arguments. The last call calculates time differences between timeStamps.
timer(timer_table = data.table(), end = FALSE, ...)
timer_table |
A data.table containing the timer log to continue from. Defaults to an empty 'data.table(). |
end |
A logical, inidicating the end of the timer, defaulted to FALSE. 'timer()' calls must be placed at the beginning of each part : therefore, this 'closing' step is necessary to compute time for the last part. Time differences between timeStamps are calculated only when closing the timer. |
... |
Additional specifications. Use named arguments to provide documentation on the code parts you are timing : naming the current step, the version of the code you are trying, or any other useful specification |
A 'data.table' containing the original data, plus one new timeStamp, and optionally computed time differences :
'timeStamp': The current timeStamp ('POSIXct').
'timeStamp_num': timeStamp converted to numeric, useful for intermediary calculations.
'dt_num': The time difference in seconds between consecutive rows as a numeric value.
'dt_text': The formatted time difference in seconds with milliseconds as a character string.
Additional columns for any information provided by the user via '...'. It allows documentation about the current step running, substeps, which version is being tested, ...
# compare code speed between using a loop, or the mean() function
library(data.table)
library(dplyr)
tmr <- data.table() # Initialize timer
vec <- rnorm(1e6) # Example vector
tmr <- timer(tmr, method = "loop") # timeStamp : 1st step =================
total <- 0
for (i in seq_along(vec)) total <- total + vec[i]
mean_loop <- total / length(vec)
tmr <- timer(tmr, method = "mean()") # timeStamp : 1st step =================
mean_func <- mean(vec)
tmr <- timer(tmr, end = TRUE) # timeStamp : close timer ==============
t_step1 <- tmr[method == "loop"]$dt_num
t_step2 <- tmr[method == "mean()"]$dt_num
diff_pc <- (t_step2/t_step1 - 1) * 100
diff_txt <- format(diff_pc, nsmall = 0, digits = 1)
# view speed difference
print(tmr %>% select(-matches("_num$")))
paste0("speed difference : ", diff_txt, "%")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.