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

to deal with memory leaking: added instance method destroy! to Rglpk::Problem #2

Merged
merged 3 commits into from Jan 3, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions lib/rglpk.rb
Expand Up @@ -70,6 +70,14 @@ def initialize
Glpk_wrapper.glp_create_index(@lp)
end

def destroy!
Glpk_wrapper.glp_delete_prob(@lp)

Glpk_wrapper.delete_intArray(@_ia)
Glpk_wrapper.delete_intArray(@_ja)
Glpk_wrapper.delete_doubleArray(@_ar)
end

def name=(n)
Glpk_wrapper.glp_set_prob_name(@lp, n)
end
Expand Down Expand Up @@ -162,6 +170,10 @@ def set_matrix(v)
Glpk_wrapper.doubleArray_setitem(ar, y + 1, x)
end

@_ia = ia
@_ja = ja
@_ar = ar

Glpk_wrapper.glp_load_matrix(@lp, v.size, ia, ja, ar)
end

Expand Down
75 changes: 75 additions & 0 deletions test/test_memory_prof.rb
@@ -0,0 +1,75 @@
require File.expand_path('helper', File.dirname(__FILE__))

class TestMemoryProf < Test::Unit::TestCase
def test_memory_prof
while true
1000.times do |i|
_test_example
end

out = `ps aux | grep "ruby test/test_memory_prof.rb"`
puts out.split("\n")[0]
end
end

def _test_example
# The same Brief Example as found in section 1.3 of
# glpk-4.44/doc/glpk.pdf.
#
# maximize
# z = 10 * x1 + 6 * x2 + 4 * x3
#
# subject to
# p: x1 + x2 + x3 <= 100
# q: 10 * x1 + 4 * x2 + 5 * x3 <= 600
# r: 2 * x1 + 2 * x2 + 6 * x3 <= 300
#
# where all variables are non-negative
# x1 >= 0, x2 >= 0, x3 >= 0
#
p = Rglpk::Problem.new
p.name = "sample"
p.obj.dir = Rglpk::GLP_MAX

rows = p.add_rows(3)
rows[0].name = "p"
rows[0].set_bounds(Rglpk::GLP_UP, 0, 100)
rows[1].name = "q"
rows[1].set_bounds(Rglpk::GLP_UP, 0, 600)
rows[2].name = "r"
rows[2].set_bounds(Rglpk::GLP_UP, 0, 300)

cols = p.add_cols(3)
cols[0].name = "x1"
cols[0].set_bounds(Rglpk::GLP_LO, 0.0, 0.0)
cols[1].name = "x2"
cols[1].set_bounds(Rglpk::GLP_LO, 0.0, 0.0)
cols[2].name = "x3"
cols[2].set_bounds(Rglpk::GLP_LO, 0.0, 0.0)

p.obj.coefs = [10, 6, 4]

p.set_matrix([
1, 1, 1,
10, 4, 5,
2, 2, 6
])

p.simplex
z = p.obj.get
x1 = cols[0].get_prim
x2 = cols[1].get_prim
x3 = cols[2].get_prim

result = "z = %g; x1 = %g; x2 = %g; x3 = %g" % [z, x1, x2, x3]
assert_equal "z = 733.333; x1 = 33.3333; x2 = 66.6667; x3 = 0", result
assert_equal Rglpk::GLP_NU, rows[0].get_stat
assert_equal 100, rows[0].get_prim
assert_equal 3.333333333333333, rows[0].get_dual
# File.delete("test.lp") rescue Errno::ENOENT
# p.write_lp("test.lp")
# assert File.exists?("test.lp")

p.destroy!
end
end