Ruby scripts can become expensive quickly and this handy method can let you know if something is getting out of control. This script will read out of the %cpu on a OSX system.

def cpu_usage
  cpu = `ps -o %cpu #{$$}`
  cpu.strip.gsub(/\n/, ":")
p cpu_usage
#=> "%CPU: 0.0"
(0..25000).each do |int|
  p cpu_usage
#=> %CPU: 34.7" 
#=> %CPU: 35.1" 
#=> ...

There are many other ps commands you could place here that should help to gain an understanding of how the system is reacting to you code.


One thought on “Daily Ruby Tips #127 – Check System Usage in Ruby Code

  1. Tip Follower says:

    Great :)

Leave a Reply

Your email address will not be published. Required fields are marked *