Skip to content

Instantly share code, notes, and snippets.

@mmasashi
Last active December 11, 2015 16:08
Show Gist options
  • Save mmasashi/4625265 to your computer and use it in GitHub Desktop.
Save mmasashi/4625265 to your computer and use it in GitHub Desktop.
Simple vmstat command with vmstat gem (gem install vmstat)
#!/usr/bin/env ruby
#
# Simple vmstat command with vmstat gem
# ex)
# $ ./ruby-vmstat.rb 1 3
# cpu0 cpu1 cpu2 cpu3 memory load average
# i i i i free 1m 5m 15m
# 88.4 96.8 89.0 96.9 1093 0.5 0.9 0.9 2013-01-24 09:09:09 -0800
# 88.4 96.8 89.0 96.9 1093 0.5 0.9 0.9 2013-01-24 09:09:10 -0800
# 88.4 96.8 89.0 96.9 1093 0.5 0.9 0.9 2013-01-24 09:09:11 -0800
require 'vmstat'
def to_per(num)
sprintf("%.1f", num*100)
end
def to_ldavg(avg)
sprintf("%.1f", avg)
end
def print_cpu_info(cpus, header=0)
case header
when 1
1.upto(cpus.size) do |num|
#print "cpu#{num-1}\t\t\t\t\t"
print "cpu#{num-1}\t"
end
return
when 2
1.upto(cpus.size) do |num|
#print "n\tu\ts\tni\ti\t"
print "i\t"
end
return
end
cpus.each do |c|
total = c.user + c.system + c.idle
list = []
#list << c.num
#list << [c.user, c.system, c.idle].map{|v| to_per(v.to_f/total)}
list << [c.idle].map{|v| to_per(v.to_f/total)}
#list << c.nice
print list.join("\t") + "\t"
end
end
def print_memory_info(mem, header=0)
case header
when 1
print "memory\t"
return
when 2
print "free\t"
return
end
print "#{mem.free/1024}\t"
end
def print_load_avg_info(ldavg, header=0)
case header
when 1
print "load average \t"
return
when 2
print "1m\t5m\t15m\t"
return
end
print "#{to_ldavg ldavg.one_minute}\t#{to_ldavg ldavg.five_minutes}\t#{to_ldavg ldavg.fifteen_minutes}\t"
end
def print_time
print Time.now
end
def dump_all_info(header=false)
cpus = Vmstat.cpu
memory = Vmstat.memory
load_avg = Vmstat.load_average
net_ifs = Vmstat.network_interfaces
if header
print_cpu_info(cpus, 1)
print_memory_info(memory, 1)
print_load_avg_info(load_avg, 1)
puts
print_cpu_info(cpus, 2)
print_memory_info(memory, 2)
print_load_avg_info(load_avg, 2)
puts
return
end
print_cpu_info(cpus)
print_memory_info(memory)
print_load_avg_info(load_avg)
print_time
puts
end
def dump_loop(sleep_sec, loop_num)
i=0
while true
dump_all_info
i += 1
break unless i < loop_num or loop_num == 0
sleep sleep_sec
end
end
dump_all_info true
sleep_sec = ARGV[0] ? ARGV[0].to_i : 0
loop_num = ARGV[1] ? ARGV[1].to_i : 0
loop_num = 1 if sleep_sec == 0
dump_loop(sleep_sec, loop_num)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment