Last active
June 23, 2021 23:27
-
-
Save Zyndoras/f35cdce77cc3daa342d5991165169864 to your computer and use it in GitHub Desktop.
Log CPU usage percentage per core
This file contains 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
#!/usr/bin/env ruby | |
$stdout.sync = true | |
cpu_last = {} | |
cpu_last_sum = {} | |
loop do | |
cpus = IO.readlines('/proc/stat').select { |line| line.start_with?('cpu') } | |
current = {} | |
cpus.each do |cpu| | |
stats = cpu.split(' ') | |
name = stats[0] | |
cpu_now = stats[1..].map(&:to_i) | |
cpu_last[name] ||= cpu_now | |
cpu_sum = cpu_now.inject(:+) | |
cpu_delta = cpu_sum - cpu_last_sum[name].to_i | |
cpu_idle_delta = cpu_now[3] - cpu_last[name][3].to_i | |
cpu_used = cpu_delta - cpu_idle_delta | |
cpu_usage = (100 * cpu_used / cpu_delta) | |
current[name] = cpu_usage | |
cpu_last[name] = cpu_now | |
cpu_last_sum[name] = cpu_sum | |
end | |
puts "#{Time.now} #{current.map { |name, usage| "#{name}: #{usage}%" }.join(' ')}" | |
sleep(1) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment