Skip to content

Instantly share code, notes, and snippets.

@nathwill
Created September 4, 2013 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathwill/6441103 to your computer and use it in GitHub Desktop.
Save nathwill/6441103 to your computer and use it in GitHub Desktop.
OpenVZ CPU Calculations
#!/usr/bin/env ruby
require 'fileutils'
def get_freq
File.readlines('/proc/cpuinfo').each do |line|
next unless line.match(/^cpu MHz/)
return line.split(/:/).last.strip.to_f * 1048576
end
end
def get_stats
vals = Array.new
File.readlines('/proc/vz/vestat').each do |line|
# skip garbage
next if line.match(/^Version/)
next if line.match(/^$/)
next if line.match(/VEID/)
# headers and vals
line.gsub!(/\s+/, ' ')
vals = line.strip.split(/\s/)
end
return {:veid => vals[0],
:user => vals[1],
:system => vals[3],
:uptime_jiffies => vals[4],
:uptime_cycles => vals[7],
:used => vals[8]}
end
# Calculations:
# jiffies: (user, nice, system, uptime)
# seconds = measurement / jiffies_per_second
# cycles: (idle, strv, uptime, used, maxlat, totlat, numsched)
# seconds = measurement / frequency_of_your_cpu
def calc_stats (old_stats, new_stats, freq)
elapsed_jiffies = new_stats[:uptime_jiffies].to_f - old_stats[:uptime_jiffies].to_f
elapsed_cycles = new_stats[:uptime_cycles].to_f - old_stats[:uptime_cycles].to_f
cpu = ((new_stats[:used].to_f - old_stats[:used].to_f) / elapsed_cycles) * 100
user = ((new_stats[:user].to_f - old_stats[:user].to_f) / elapsed_jiffies) * 100
system = ((new_stats[:system].to_f - old_stats[:system].to_f) / elapsed_jiffies) * 100
return {:cpu => cpu, :user => user, :system => system}
end
# load starting data
freq = get_freq
new_stats = get_stats
i = 0
while i < 10 do
old_stats = new_stats
new_stats = get_stats
summary = calc_stats(old_stats, new_stats, freq)
puts "\n CYCLE #{i}\n-------------"
puts "CPU Use: #{summary[:cpu]} %"
puts "User: #{summary[:user]} %"
puts "System %: #{summary[:system]} %"
i += 1
sleep 10
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment