Sets up a timer which can later be summoned by string_magic() functions via the .timer, .timer_lap and .timer_total variables. Useful to report timings within functions with the function cat_magic() or message_magic().

timer_magic()

Value

This function does not return anything and is only intended to be used in conjunction with future calls of string_magic().

Details

This functions sets up a timer with base::Sys.time(). This timer can then be tracked and modified with the .timer, .timer_lap and .timer_total variables within cat_magic() or message_magic().

Note that the timer is precise at +/- 1ms, hence it should not be used to time algorithms with very short execution times.

It works by saving the current system time in R options (stringmagic_timer and stringmagic_timer_origin). Hence, since it uses options, it should not be used in parallel processes.

See also

Author

Laurent Berge

Examples


# simple example where we time the execution of some elements in a function
# we trigger the message conditionally on the value of the argument `debug`.
rnorm_crossprod = function(n, mean = 0, sd = 1, debug = FALSE){
  # we set the timer
  timer_magic()
  # we compute some stuff
  x = rnorm(n, mean, sd)
  # we can report the time with .timer
  message_magic("{15 align ! Generation}: {.timer}", .trigger = debug)
  
  res = x %*% x
  message_magic("{15 align ! Product}: {.timer}",
                "{15 align ! Total}: {.timer_total}", 
                .sep = "\n", .trigger = debug)
  res
}

rnorm_crossprod(1e5, TRUE)
#>          [,1]
#> [1,] 200202.7