Created
March 1, 2015 18:46
-
-
Save aasmith/906568a8a69bf6e99a01 to your computer and use it in GitHub Desktop.
Print CPU usage in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Vmstat provides cumulative cpu ticks for each of the three categories (system, user, idle) since the machine booted.