Using external commands on Ruby like ps
through using backticks will fork the current process for the duration of running the command. This means that if your Ruby process consumes 300mb, you will need another 300mb just to run any of these `ps -o rss #{$$}`.strip.split.last.to_i
solutions.
On linux based systems you can get process memory information by reading /proc/PID/statm
. The second field is the Resident Set Size in number of kernel pages. Converting the RSS pages to bytes requires you to figure out the kernel page size (most likely 4096).
Here's sample code how to get the rss in kilobytes, works on Linux. I don't know how to do this on OSX or other systems.
module MemInfo
# This uses backticks to figure out the pagesize, but only once
# when loading this module.
# You might want to move this into some kind of initializer
# that is loaded when your app starts and not when autoload
# loads this module.
KERNEL_PAGE_SIZE = `getconf PAGESIZE`.chomp.to_i rescue 4096
STATM_PATH = "/proc/#{Process.pid}/statm"
STATM_FOUND = File.exist?(STATM_PATH)
def self.rss
STATM_FOUND ? (File.read(STATM_PATH).split(' ')[1].to_i * KERNEL_PAGE_SIZE) / 1024 : 0
end
end
# >> MemInfo.rss
# => 251944