Skip to content

Instantly share code, notes, and snippets.

@Mark24Code
Forked from pvdb/process_rss.rb
Created January 21, 2022 07:22
Show Gist options
  • Save Mark24Code/1bda34843884e3723a783a4b865e3bc5 to your computer and use it in GitHub Desktop.
Save Mark24Code/1bda34843884e3723a783a4b865e3bc5 to your computer and use it in GitHub Desktop.
Get real memory (resident set) used by current Ruby process
#
# This first version should work on Mac OS X and Linux, but it spawns a process
#
# http://stackoverflow.com/questions/7220896/
# https://github.com/rdp/os/blob/master/lib/os.rb#L127
# http://www.ruby-doc.org/core-2.0/Process.html
#
# the real memory (resident set) size of the process (in 1_024 byte units).
def Process.rss() `ps -o rss= -p #{Process.pid}`.chomp.to_i ; end
#
# This second version depends on the /proc filesystem, so won't work on Mac OS X
#
# https://www.kernel.org/doc/Documentation/filesystems/proc.txt
# >> Table 1-3 << Contents of the statm files (as of 2.6.8-rc3)
#
# Note that this implementation assumes that the size of memory
# pages is 4_096 bytes, ie. 4kB, which is a widespread default!
#
# However, it is probably best to check this assumption on your
# architecture, using `getconf PAGESIZE` or `getconf PAGE_SIZE`
#
# returns detailed information about the process memory usage (as recorded in the "/proc/$$/statm" proc fs file)
def Process.statm() Hash[%i{size resident shared trs lrs drs dt}.zip(open("/proc/#{Process.pid}/statm").read.split)] ; end
# the real memory (resident set) size of the process (in 1_024 byte units, assuming a 4kB memory page size)
def Process.rss() Process.statm[:resident].to_i * 4 ; end
#
# Some pretty formatting, on top of either of the above implementations
#
def Process.pretty_rss(rss = Process.rss) rss.to_s.gsub(/(\d)(?=(\d{3})+(\..*)?$)/,'\1,') + " kilobytes" ; end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment