Skip to content

Instantly share code, notes, and snippets.

@cr0t
Created January 22, 2018 14:04
Show Gist options
  • Select an option

  • Save cr0t/14494775a1db7f6c3b7d1811a626189c to your computer and use it in GitHub Desktop.

Select an option

Save cr0t/14494775a1db7f6c3b7d1811a626189c to your computer and use it in GitHub Desktop.
`sudo purge`
memory_by_process = Hash.new(0)
processes = `ps aux`
m_bytes = processes.split("\n").reduce(0) { |memo, prc|
fields = prc.split(/\s+/)
mem_bytes = fields[5].to_i
prc_name = fields[10...fields.length].join(' ')
prc_name = 'Chrome.app' if prc_name.include? 'Chrome'
memory_by_process[prc_name] += mem_bytes
memo + mem_bytes
}
mega_bytes = (m_bytes / 1024.0).round(2)
total_memory = `sysctl hw.memsize`.match(/\d+/)[0].to_i # hw.memsize: 17179869184
total_memory_in_megabytes = total_memory / 1024 / 1024
one_percent_from_total_memory = (total_memory_in_megabytes / 100.0)
used_percent = (mega_bytes / one_percent_from_total_memory).round(2)
puts "Total: #{mega_bytes}MBs of #{total_memory_in_megabytes}MBs of RAM is used by processes (#{used_percent}% is used)"
puts "TOP-20:"
top_ten_bytes_sum = 0
memory_by_process.sort_by { |k, value| value }.reverse[0...20].each { |mem|
prc_name = mem[0][0...96]
prc_name += '...' if mem[0].length > 96
m_bytes = mem[1] / 1024.0
mega_bytes = m_bytes.round(2)
percent = (mega_bytes / one_percent_from_total_memory).round(2)
puts "#{mega_bytes} #{percent}%\t#{prc_name}"
top_ten_bytes_sum += mem[1]
}
mega_bytes = sprintf("%.2f", top_ten_bytes_sum / 1024.0)
puts "TOP-20 summary uses #{mega_bytes} Mb of memory"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment