Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FR: accessor function for unit? #14

Open
ugroempi opened this issue Nov 17, 2018 · 1 comment
Open

FR: accessor function for unit? #14

ugroempi opened this issue Nov 17, 2018 · 1 comment
Assignees

Comments

@ugroempi
Copy link

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
Copy link
Owner

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
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants