Skip to content

Instantly share code, notes, and snippets.

@schneems
Created June 12, 2014 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schneems/1fec6ce7bb9a46bb0ac2 to your computer and use it in GitHub Desktop.
Save schneems/1fec6ce7bb9a46bb0ac2 to your computer and use it in GitHub Desktop.
require 'pathname'
require 'bigdecimal'
KB_TO_BYTE = 1024 # 2**10 = 1024
MB_TO_BYTE = 1_048_576 # 1024**2 = 1_048_576
GB_TO_BYTE = 1_073_741_824 # 1024**3 = 1_073_741_824
CONVERSION = { "kb" => KB_TO_BYTE, "mb" => MB_TO_BYTE, "gb" => GB_TO_BYTE }
ROUND_UP = BigDecimal.new("0.5")
def linux_memory(file)
lines = file.each_line.select {|line| line.match /^(Pss|Private_Dirty|Swap)/ }
private_dirty = 0
swap = 0
pss = 0
return if lines.empty?
lines.reduce(0) do |sum, line|
line.match(/(?<name>(^.+)):\s*(?<value>(\d*\.{0,1}\d+))\s+(?<unit>\w\w)/) do |m|
value = BigDecimal.new(m[:value])
unit = m[:unit].downcase
case m[:name]
when "Private_Dirty"
private_dirty += CONVERSION[unit] * value
when "Pss"
pss += CONVERSION[unit] * value
when "Swap"
swap += CONVERSION[unit] * value
end
end
sum
end
return private_dirty, pss, swap
rescue Errno::EACCES
return 0, 0, 0
end
def total_system_memory
sum = 0
Dir["/proc/*"].each do |dir|
file = Pathname.new(dir).join("smaps")
if file.exist?
private_dirty, pss, swap = linux_memory(file)
sum += private_dirty + swap
end
end
(sum/BigDecimal.new(MB_TO_BYTE)).to_f
end
Thread.new do
loop do
sleep 1
begin
puts "Experiment: measure#memory_total=#{total_system_memory}"
rescue => e
puts "Error: #{e.inspect}\n #{e.backtrace}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment