c6p-cq
Last Updated: February 25, 2016
·
3.765K
· bryanp

Measuring memory usage in Ruby

I've recently been working on fixing a memory leak in a Ruby web server. I dug up this code snippet I found somewhere and wanted to share. Works on OSX; probably Linux too.

puts `ps -o rss= -p #{$$}`.to_i

And to force garbage collection, run this before measuring:

GC.start

Happy tuning!

3 Responses
Add your response

13293

Not working at all.
➜ ~ puts ps -o rss= -p #{$$}.to_i

ps: option requires an argument -- p
usage: ps [-AaCcEefhjlMmrSTvwXx] [-O fmt | -o fmt] [-G gid[,gid...]]
[-g grp[,grp...]] [-u [uid,uid...]]
[-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]
ps [-L]

over 1 year ago ·
13296

Wat. Here's what it does for me:

irb(main):005:0> `ps -o rss= -p #{$$}`.to_i
=> 13188

OSX or Linux?

over 1 year ago ·
17556

@rozzy probably you already noticed, this has to run in a ruby script as it gets the process id as input and provides memory usage as output. Some details: --- Backticks operator places your command in a shell script and returns it's result (there are many other variants, http://goo.gl/HGg2ee). --- The double dollar sign is a ruby method and retrieves the script's current process ID. --- The following code is a bash script which finds the memory usage of a particular process id: ps -o rss= -p PROCESS_ID

over 1 year ago ·