Time an expression or chunk of R code with `system.time()` and return both the results of evaluating the expression and the execution time in a list.
time_this(code, time_as = c("list", "attr"))
code | An expression or code chunk (wrapped in curly brackets) to time. |
---|---|
time_as | character; return the execution time and results as list elements ("list") or return results with time as an attribute ("attr"). |
A list with elements `result` and `time`, containing the results of evaluating `code` and the execution time, respectively. If `time_as = "attr"`, the result will be returned directly with the time stored as an attribute.
# time a simple expression time_this(mean(rnorm(1e6)))#> $result #> [1] 0.000685264 #> #> $time #> user system elapsed #> 0.069 0.001 0.071 #># time a code chunk time_this({ x <- (1:1e6) / 1e6 y = 2 * x + 1 + rnorm(x) lm(y ~ x) })#> $result #> #> Call: #> lm(formula = y ~ x) #> #> Coefficients: #> (Intercept) x #> 1.001 2.000 #> #> #> $time #> user system elapsed #> 0.230 0.049 0.279 #># time can also be stored as an attribute time_this(mean(rnorm(1e6)), time_as = "attr")#> [1] -0.000592503 #> attr(,"time") #> user system elapsed #> 0.073 0.001 0.073