Skip to content

Instantly share code, notes, and snippets.

@merolagio
Last active July 16, 2019 06:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save merolagio/2bcff0b01235cc829b0b48f76693a466 to your computer and use it in GitHub Desktop.
Save merolagio/2bcff0b01235cc829b0b48f76693a466 to your computer and use it in GitHub Desktop.
[R] microbenchmark relative summary
mbm_rel <- function(x, d, relname = NULL, relpos = 1, inverse = FALSE, reltime = TRUE, unit){
## produces relative summaries from microbenchmark output ================
## ---- arguments ----------------------------------------------------------
## x a microbenchmark output object with two or more methods
## d number of rows to consider (in the order of rows of x)
## relname is name of metod for relative results
## relpos is the position of target metod for relative results relmethod/othermethod
## inverse = TRUE compute othermethods/relmethod or viceversa
## reltime, if true prints the time taken by the method, otherwise sets its values to 1
## unit can be “ns”, “us”, “ms”, “s”, “t”, “hz”, “khz”, “mhz”, “eps”, “f”
## default unit same as object. see microbenchmark documentation
## -- author Giovanni Merola lsspaca@gmail.com ============================
require(microbenchmark)
if (missing(unit)){
p <- summary(x)
unit <- attr(p, "unit")
}
else
if(unit != "m"){
p <- summary(x, unit = unit)
unit <- attr(p, "unit")
}
else{
p <- summary(x, unit = "s")
p[,2:7] <- p[,2:7]/60
unit <- "minutes"
}
## moves rel method on top
if (!is.null(relname))
indt <- which(p$expr == relname)
else
indt <- relpos
if (indt > 1)
p <- p[ c(indt, (1:nrow(p))[-indt]), ]
n <- p$neval
rown <- as.character(p$expr)
p <- p[,-1]
first <- p[1, ]
p <- as.matrix(p)
if (missing(d))
d <- nrow(p)
else
if(d > nrow(p))
stop(paste("too many methods required, only", nrow(p), "available"))
else
p <- p[1:d, ]
p[2:d, ] <- t(t(p[2:d, ])/p[1, ])
if (reltime == FALSE)
p[1, 1:6] <- 1
rownames(p) <- rep(NA, d)
if (inverse == FALSE){
p[ 2:d, 1:6]<- 1/p[ 2:d, 1:6]
rownames(p)[2:d] <- paste0(rown[1], "/", rown[2:d])
}
else
rownames(p)[2:d] <- paste0(rown[2:d], "/", rown[1])
if (reltime == TRUE)
rownames(p)[1] <- paste(rown[1], "time")
else
rownames(p)[1] <- rown[1]
p <- round(p , 3)
p[,7] <- n[1:d]
p <- as.data.frame(p)
attr(p, "unit") <- unit
cat("Unit: ", unit, "\n", sep = "")
return(p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment