Last Updated: July 23, 2020
· 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:


Happy tuning!

Note from Coderwall team: we've made up our own list of application performance monitoring tools.

3 Responses
Add your response

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 ·

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 ·

@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, --- 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 ·