Skip to content

Instantly share code, notes, and snippets.

@aasmith
Created March 1, 2015 18:46
Show Gist options
  • Select an option

  • Save aasmith/906568a8a69bf6e99a01 to your computer and use it in GitHub Desktop.

Select an option

Save aasmith/906568a8a69bf6e99a01 to your computer and use it in GitHub Desktop.
Print CPU usage in ruby
require "vmstat" # gem install vmstat
CPU_DETAIL = false # set to true if you want to see details for each cpu.
CPU_USAGE = "CPU %s: %5.1f%% sys %5.1f%% user %5.1f%% idle"
def delta prev, curr
all = prev.cpus.zip(curr.cpus).map do |prev_cpu, curr_cpu|
system = curr_cpu.system - prev_cpu.system
user = curr_cpu.user - prev_cpu.user
idle = curr_cpu.idle - prev_cpu.idle
total = system + user + idle
percentages = [system, user, idle].map do |ticks|
(ticks / total.to_f) * 100.0
end
puts CPU_USAGE % [prev_cpu.num, *percentages] if CPU_DETAIL
percentages
end
averages = all.transpose.map do |stats|
total = stats.reduce :+
total / stats.size.to_f
end
puts CPU_USAGE % ["A", *averages]
end
prev_sample = Vmstat.snapshot
loop do
sleep 1
sample = Vmstat.snapshot
delta(prev_sample, sample)
prev_sample = sample
end
@aasmith
Copy link
Author

aasmith commented Mar 1, 2015

Vmstat provides cumulative cpu ticks for each of the three categories (system, user, idle) since the machine booted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment