Skip to content

Instantly share code, notes, and snippets.

@rwjblue
Created March 2, 2013 16:43
Show Gist options
  • Save rwjblue/5071864 to your computer and use it in GitHub Desktop.
Save rwjblue/5071864 to your computer and use it in GitHub Desktop.
Test Ruby's ability to release memory back to system.
Ruby 1.9.3-p392
===========================================================
All memory used before 1st run - 7 MB
Memory consumed by 1st run of eat_up_memory - 445 MB
All memory used before 2nd run - 452 MB
Memory consumed by 2nd run of eat_up_memory - 20 MB
All memory used before 3rd run - 472 MB
Memory consumed by 3rd run of eat_up_memory - 5 MB
Memory used before explicit GC.start - 478 MB
Memory used after explicit GC.start - 284 MB
Ruby 2.0.0-p0
===========================================================
All memory used before 1st run - 8 MB
Memory consumed by 1st run of eat_up_memory - 468 MB
All memory used before 2nd run - 476 MB
Memory consumed by 2nd run of eat_up_memory - 84 MB
All memory used before 3rd run - 561 MB
Memory consumed by 3rd run of eat_up_memory - 19 MB
Memory used before explicit GC.start - 580 MB
Memory used after explicit GC.start - 511 MB
Ruby 2.0.0-p0
RUBY_FREE_MIN=200000 RUBY_GC_MALLOC_LIMIT=60000000
===========================================================
All memory used before 1st run - 8 MB
Memory consumed by 1st run of eat_up_memory - 553 MB
All memory used before 2nd run - 561 MB
Memory consumed by 2nd run of eat_up_memory - 0 MB
All memory used before 3rd run - 562 MB
Memory consumed by 3rd run of eat_up_memory - 25 MB
Memory used before explicit GC.start - 588 MB
Memory used after explicit GC.start - 406 MB
require 'securerandom'
def memory_usage
`ps -o rss= -p #{Process.pid}`.to_i
end
def profile_memory(comment)
before = memory_usage
block_given? ? yield : before = 0
puts "#{comment.ljust(50)} - #{(memory_usage - before) / 1024} MB"
end
def eat_up_memory
strings = []
1_000_000.times do
strings << SecureRandom.base64(255)
end
nil
end
['1st','2nd','3rd'].each do |count|
profile_memory "All memory used before #{count} run"
profile_memory("Memory consumed by #{count} run of eat_up_memory") do
eat_up_memory
end
end
profile_memory "Memory used before explicit GC.start"
GC.start
profile_memory "Memory used after explicit GC.start"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment