microbenchmark icon indicating copy to clipboard operation
microbenchmark copied to clipboard

FR: accessor function for unit?

Open ugroempi opened this issue 7 years ago • 1 comments
trafficstars

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

ugroempi avatar Nov 17 '18 14:11 ugroempi

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
}

joshuaulrich avatar Nov 22 '18 13:11 joshuaulrich