Modify a function so its execution is timed with `system.time()` and both the results of the funciton call and the execution time are returned as a list.

add_timer(.f, time_as = c("list", "attr"))

Arguments

.f

A function to modify to add a timer.

time_as

character; return the execution time and results as list elements ("list") or return results with time as an attribute ("attr").

Value

Wrapped function that returns a list with components `result` and `time`. If `time_as = "attr"`, the result will be returned directly with the time stored as an attribute.

Examples

mean_timed <- add_timer(mean) mean_timed(rnorm(1e6))
#> $result #> [1] -0.0001087791 #> #> $time #> user system elapsed #> 0.074 0.003 0.077 #>
lm_timed <- add_timer(lm) x <- (1:1e6) / 1e6 y = 2 * x + 1 + rnorm(x) lm_timed(y ~ x)
#> $result #> #> Call: #> .f(formula = ..1) #> #> Coefficients: #> (Intercept) x #> 1.003 1.996 #> #> #> $time #> user system elapsed #> 0.261 0.052 0.312 #>
# time can also be stored as an attribute mean_timed_a <- add_timer(mean, time_as = "attr") mean_timed_a(rnorm(1e6))
#> [1] -0.0002556792 #> attr(,"time") #> user system elapsed #> 0.077 0.000 0.077