Skip to content

Instantly share code, notes, and snippets.

@andruby
Created January 23, 2010 17:17
Show Gist options
  • Save andruby/284694 to your computer and use it in GitHub Desktop.
Save andruby/284694 to your computer and use it in GitHub Desktop.
Sample the CPU Load and Memory usage of an application over time and returns the average, standard deviation and min-max range.
# Sample the CPU Load and Memory usage of an application over time and
# returns the average, standard deviation and min-max range.
# processname to check as $1, number of samples as $2
# eg: ruby ps_avg.rb safari 100
process_name = ARGV[0]
sample_count = ARGV[1] || 120
samples_per_seconds = 3
sleep_time = (1/samples_per_seconds.to_f)
puts "Sampling: #{process_name}, taking #{sample_count} samples (#{samples_per_seconds} per second)"
## Expand the Enumerable module with Basic statistics
module Enumerable
# sum of an array of numbers
def sum
return self.inject(0){|acc,i|acc +i}
end
# average of an array of numbers
def average
return self.sum/self.length.to_f
end
# variance of an array of numbers
def sample_variance
avg=self.average
sum=self.inject(0){|acc,i|acc +(i-avg)**2}
return(1/self.length.to_f*sum)
end
# standard deviation of an array of numbers
def standard_deviation
return Math.sqrt(self.sample_variance)
end
end
## close module Enumerable
## Print floats with 2 decimals
class Float
def to_s
sprintf("%.2f", self)
end
end
## Method that does the fetching of cpu load and mem usage
## Tested on MacOS X and FreeBSD. The regexp might need tweaking for Linux
def get_cpu_and_mem(pname)
output = `ps uxa`
regexp = /[a-z]+\s+[0-9]+\s+([0-9,\.]+)\s+[0-9,\.]+\s+\d+\s+(\d+)/
lines = output.split("\n").select{ |x| x.downcase.include?(pname.downcase) && !x.include?("ruby") }
lines.collect do |line|
line.scan(regexp).first.collect{ |x| x.gsub(',','.').to_f }
end.inject([0,0]){ |x,sum| [x[0] + sum[0],x[1] + sum[1]] }
end
## Loop for sample_count times and gather the samples in the samples array
samples = {:cpu => [], :mem => []}
sample_count.to_i.times do
cpu, mem = get_cpu_and_mem(process_name)
samples[:cpu] << cpu
samples[:mem] << mem/1024.0
sleep sleep_time
end
def print_stats(array,name)
print "Average #{name}: #{array.average}\t"
print "StdDev: #{array.standard_deviation}\t"
puts "Range: #{array.min} - #{array.max}"
end
print_stats(samples[:cpu],"cpu load (%)")
print_stats(samples[:mem],"mem use (MB)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment