joshuaulrich / microbenchmark

Infrastructure to accurately measure and compare the execution time of R expressions
Other
95 stars 24 forks source link

FR: accessor function for unit? #14

Open ugroempi opened 6 years ago

ugroempi commented 6 years ago

Hi Joshua,

it would be very nice to have an accessor function for the unit used, because it is not easy to infer from the documentation how to access the unit (e.g. for annotation purposes of a boxplot comparison, where the default axis annotation does not satisfy my curiosity). It is easy, but an occasional user doesn't know that it is. A quick (but maybe inefficient) proposal would be something like:

unit <- function(object, unit, ...) attr(summary(object, unit, ...), "unit")

Best, Ulrike

joshuaulrich commented 5 years ago

Thanks for the suggestion! I agree this would be useful. Here's an implementation that might be a bit more efficient:

unit <- function(object, ...) { 
  unit <- attr(object, "unit")
  if (is.null(unit))
    unit <- getOption("microbenchmark.unit", "t")
  if (unit != "relative") {
    find_prefix <- microbenchmark:::find_prefix
    x <- object$time
    if (unit == "t") {
      unit <- find_prefix(x * 1e-09, minexp = -9, maxexp = 0, mu = FALSE)
      unit <- sprintf("%ss", unit)
    } else if (unit == "f") {
      unit <- find_prefix(1e+09 / x, minexp = 0, maxexp = 6, mu = FALSE)
      unit <- sprintf("%shz", unit)
    }
    unit <- tolower(unit)
    unit <- switch(unit,
        ns  = "nanoseconds",
        us  = "microseconds",
        ms  = "milliseconds",
        s   = "seconds",
        eps = "evaluations per second",
        hz  = "hertz",
        khz = "kilohertz",
        mhz = "megahertz",
        "unknown")
  }
  unit
}