Created
June 27, 2013 09:29
-
-
Save repeatedly/5875185 to your computer and use it in GitHub Desktop.
Goodbye...
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
| class CpuInfo | |
| def initialize | |
| @stats = get_cpu_stats | |
| end | |
| CPU_KEYS = %W(user nice system idle iowait irq sirq) | |
| LOADAVG_KEYS = %W(loadavg1 loadavg5 loadavg15) | |
| def stats | |
| res = {} | |
| stats = get_cpu_stats | |
| diff = @stats.map.with_index { |stat, i| stats[i] - stat } | |
| total = diff.inject(0) { |sum, n| sum + n } | |
| total = 1 if total.zero? | |
| diff.each_with_index { |stat, i| | |
| res[CPU_KEYS[i]] = stat.to_f / total * 100 | |
| } | |
| loadavgs = get_loadavg_stats | |
| loadavgs.each_with_index { |stat, i| | |
| res[LOADAVG_KEYS[i]] = stat | |
| } | |
| @stats = stats | |
| res | |
| end | |
| private | |
| def get_cpu_stats | |
| File.open("/proc/stat") { |f| | |
| stats = f.gets.split(' ', CPU_KEYS.size) | |
| stats.shift | |
| return stats.map { |stat| stat.to_i } | |
| } | |
| end | |
| def get_loadavg_stats | |
| File.open("/proc/loadavg") { |f| | |
| stats = f.gets.split(' ', LOADAVG_KEYS.size) | |
| return stats.map { |stat| stat.to_f } | |
| } | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment