timer_magic: Sets up a timer that can be used within _magic functions

View source: R/string_magic_main.R

timer_magicR Documentation

Sets up a timer that can be used within ⁠_magic⁠ functions

Description

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().

Usage

timer_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.

Value

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

Author(s)

Laurent Berge

See Also

Other tools with aliases: string_clean_alias(), string_magic(), string_magic_alias(), string_ops_alias(), string_vec_alias()

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)



stringmagic documentation built on May 29, 2024, 6:04 a.m.