inst/benchmarks/knapsack.md

Knapsack

You cannot really beat the benchmark here, but I still include it as a baseline for simple examples.

library(rmpk)
library(ROI)
## ROI: R Optimization Infrastructure

## Registered solver plugins: nlminb, alabama, glpk, quadprog.

## Default solver: auto.
library(ROI.plugin.glpk)
library(magrittr)
set.seed(42)
v <- rnorm(10)
w <- rnorm(10)

roi <- function() {
  obj <- L_objective(w)
  constr <- L_constraint(v, "<=", 10)
  op <- OP(objective = obj, constraints = constr, types = rep.int("B", 10), maximum = FALSE)
  ROI::ROI_solve(op, "glpk")
}

rmpk <- function() {
  solver <- ROI_optimizer("glpk")
  model <- MIPModel(solver)
  x <- model$add_variable("x", type = "binary", i = 1:10)
  model$set_objective(sum_expr(v[i] * x[i], i = 1:10))
  model$add_constraint(sum_expr(w[i] * x[i], i = 1:10) <= 10)
  model$optimize()
}

bench::mark(
  roi(),
  rmpk(),
  check = FALSE
)
## # A tibble: 2 × 6
##   expression      min   median `itr/sec` mem_alloc `gc/sec`
##   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
## 1 roi()         1.7ms   1.81ms      527.  760.35KB     45.1
## 2 rmpk()        7.1ms   7.53ms      130.    7.91MB     60.4


dirkschumacher/rmpk documentation built on Dec. 14, 2021, 5:13 p.m.