so memory is allocated, and I do not understand why. I also tried x_val = deepcopy( getvalue( model[:x] ) ) with the same result.
In contrast:
sum_x = 0.0
foo = rand(Float64, n)
println("typeof foo: ", typeof(foo))
@time for i=1:n
sum_x += foo[i] #this sum does not
end
outputs
typeof foo: Array{Float64,1}
0.000060 seconds
which does not allocate memory and is much faster.
Do you have any suggestions why this is the case, and how to work with (intermediate) JuMP results as fast as in the second example?
Thank you, but it is not in the global scope as far as I can assess it. Here is the whole example (a simple knapsack problem), which leads to the same output:
using JuMP
using CPLEX
using Random
using LinearAlgebra
#MEMORY TEST
function memTest( model, n::Int )
sum_x = 0.0
x_val = getvalue( model[:x] )
println("typeof x_val: ", typeof(x_val))
@time for i=1:n
sum_x += x_val[i] #this sum allocates mem
end
sum_x = 0.0
foo = rand(Float64, n)
println("typeof foo: ", typeof(foo))
@time for i=1:n
sum_x += foo[i] #this sum does not
end
end
#MAIN
function main()
Random.seed!(1)
n = 100000 #nvars
C = 500000 #rhs
v = rand(1:10, n) #value
w = rand(1:10, n) #weights
#BUILD AND SOLVE KNAPSACK
model = Model( solver=CplexSolver() )
@variable( model, x[1:n], Bin )
@objective( model, Max, dot(v, x) )
@constraint( model, dot(w, x) <= C )
status = solve(model)
memTest( model, n )
end
main()
Try running @code_warntype on your function. You will probably see that the type of x_val cannot be inferred, which is causing some overhead for accessing that value later in the function.
You can either use a type annotation or a function barrier to help with performance if that is indeed the case (see the Performance Tips for details on all of this).
The getvalue call might be type unstable. Check with @code_warntype and eventually use a function barrier (described in performance tips in the manual).
The second one, which will show that getvalue(model[:x]) is returning a type which is probably inferred as ::Any. Again, this is explained in much more detail in the performance tips, so please check those out: Performance Tips · The Julia Language
There’s no need for a copy. The problem is that at compile-time, the type of that variable cannot be determined, so the compiler cannot generate optimally efficient code that uses it. Again, check out the performance tips, specifically function barriers and type annotations, either of which will work in this situation.