timethis
is a simple package for modifying functions and expressions to return both the results and the execution time in a single list.
You can install the released version of timethis from CRAN with:
Install the development version from GitHub with:
To time an expression or chunk of R code use time_this()
. This will return a list with elements result
and time
containing the results of evaluating the code and the executuion time (calculated with system.time()
), respectively.
library(timethis)
# time a simple expression
time_this(mean(rnorm(1e6)))
#> $result
#> [1] 0.0007730642
#>
#> $time
#> user system elapsed
#> 0.079 0.003 0.082
# 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.002 1.997
#>
#>
#> $time
#> user system elapsed
#> 0.289 0.054 0.344
Use add_timer()
to wrap an existing 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.
mean_timed <- add_timer(mean)
mean_timed(rnorm(1e6))
#> $result
#> [1] -0.0006774308
#>
#> $time
#> user system elapsed
#> 0.077 0.001 0.078
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.997
#>
#>
#> $time
#> user system elapsed
#> 0.137 0.057 0.195