Skip to content

Instantly share code, notes, and snippets.

@Zyndoras
Last active June 23, 2021 23:27
Show Gist options
  • Save Zyndoras/f35cdce77cc3daa342d5991165169864 to your computer and use it in GitHub Desktop.
Save Zyndoras/f35cdce77cc3daa342d5991165169864 to your computer and use it in GitHub Desktop.
Log CPU usage percentage per core
#!/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