tkoolen / Parametron.jl

Efficiently solving instances of a parameterized family of (possibly mixed-integer) linear/quadratic optimization problems in Julia
Other
73 stars 7 forks source link

Can't reproduce zero-allocation examples #103

Closed ianfiske closed 5 years ago

ianfiske commented 5 years ago

Hi, I am trying out Parametron v0.9.0 on Julia 1.1. Just running through the examples in the README.md and in the docs, and I can't seem to get the zero-allocations shown in any of the examples:

using OSQP
optimizer = OSQP.Optimizer()

# create a Parametron.Model, which holds problem information
using Parametron
using Random, LinearAlgebra
model = Model(optimizer)

# create decision variables and parameters
n = 8; m = 2
x = [Variable(model) for _ = 1 : n]
A = Parameter(rand!, zeros(n, n), model)
b = Parameter(rand!, zeros(n), model)
C = Parameter(rand!, zeros(m, n), model)
d = Parameter(zeros(m), model) do d
    # do syntax makes it easy to create custom Parameters
    rand!(d)
    d .*= 2
end

# the @expression macro can be used to create 'lazy' expressions,
# which can be used in constraints or the objective function, and
# can be evaluated at a later time, automatically updating the
# Parameters in the process (if needed).
residual = @expression A * x - b

# set the objective function
@objective(model, Minimize, residual ⋅ residual)

# add the constraints. You could have multiple @constraint calls
# as well. ==, <=, and >= are supported.
@constraint(model, C * x == d)

solve!(model)
value.(model, x)

solve!(model)

using BenchmarkTools
@btime solve!($model)

gives

201.557 μs (12 allocations: 384 bytes)

Is there some change needed to reproduce the zero allocations?

blegat commented 5 years ago

It may be due to the fact this is in global space. For instance simply calling @time in global space gives 160 bytes of allocation

julia> function f() end
f (generic function with 1 method)

julia> @time f()
  0.000192 seconds (378 allocations: 25.578 KiB)

julia> @time f()
  0.000003 seconds (4 allocations: 160 bytes)
ianfiske commented 5 years ago

Thanks for that pointer @blegat . I tried moving the code into a module and my allocations actually went up! (https://gist.github.com/ianfiske/acbc4f39216b753bfea01f7b66a95f64)

However, I tried running the code in a terminal REPL instead of from Juno and that did the trick. The same code as the gist above, gives

@btime Parametron.solve!(model)
82.354 μs (0 allocations: 0 bytes)
tkoolen commented 5 years ago

Thanks, @blegat!