How to get Ruby to free OS memory

As a name, I have a ruby ​​program with a long data life. The program took all the memory, and there is a call to the system command in it hostname, and an error occurred

Cannot allocate memory - hostname

I tried GC.startand it does not work.

So how can I get ruby ​​to free memory?

OK, this is test code from other people, and finally, the error indicates that it has big_varbeen reworked. However, the memory is still not released.

require "weakref"
def report
  puts "#{param}:\t\t Memory " + `ps ax -o pid,rss | grep -E "^[[:space:]]*#{$$}"`
      .strip.split.map(&:to_i)[1].to_s + 'KB'
end
big_var = ""
#big_var = WeakRef.new(big_var)

report
big_var = 1_000_000.times.map(&:to_s)
report

big_var = WeakRef.new(big_var)

GC.start

sleep 1
report

p big_var.length

#Memory 7508KB
#Memory 61516KB
#Memory 53700KB
#test.rb:20:in `<main>': Invalid Reference - probably recycled (WeakRef::RefError)

Ok, I tried things and I don’t understand why it GC.stat[:heap_used]still remains so big after I did $big_var=nilandGC.start

puts GC.stat[:heap_used]
$big_var = []
  5000000.times { |i|
    $big_var << i.to_s
  }
puts GC.stat[:heap_used]
$big_var = nil
puts GC.stat[:heap_used]
GC.start
puts GC.stat[:heap_used]

#70
#12286
#12286
#9847    

I also use Ruby 2.1 and CentOS 6.4

+4
source share
1 answer

, WeakRef . :

require 'objspace'
require "weakref"

big_var = ""
puts "memory size: #{ObjectSpace.memsize_of big_var}"

big_var = 1_000_000.times.map(&:to_s)
puts "memory size: #{ObjectSpace.memsize_of big_var}"

big_var = WeakRef.new(big_var)
GC.start

puts "memory size: #{ObjectSpace.memsize_of big_var}"

[shreyas@arup_ruby (master)]$ ruby a.rb
memory size: 40
memory size: 11636312
memory size: 40
[shreyas@arup_ruby (master)]$

: memsize_of.

+2

All Articles