Class: Jkr::CpuUsageMonitor

Inherits:
Object
  • Object
show all
Defined in:
lib/jkr/cpu_usage.rb

Instance Method Summary collapse

Constructor Details

#initializeCpuUsageMonitor

Returns a new instance of CpuUsageMonitor.



4
5
6
7
8
9
# File 'lib/jkr/cpu_usage.rb', line 4

def initialize
  @checkpoint1 = nil
  @checkpoint2 = nil

  self.checkpoint
end

Instance Method Details

#calc_usage(stat1, stat2) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/jkr/cpu_usage.rb', line 62

def calc_usage(stat1, stat2)
  stat1_clk, stat2_clk = [stat1, stat2].map{|stat|
    stat.values.inject(&:+)
  }
  if stat1_clk > stat2_clk
    stat1, stat2, stat1_clk, stat2_clk = [stat2, stat1, stat2_clk, stat1_clk]
  elsif stat1_clk == stat2_clk
    raise RuntimeError.new("Same clock count. cannot calc usage.")
  end
  clk_diff = (stat2_clk - stat1_clk).to_f
  ret = Hash.new
  [:user, :sys, :nice, :idle].map{|key|
    ret[key] = (stat2[key] - stat1[key]) / clk_diff
  }
  ret[:total] = 1.0 - ret[:idle]

  ret
end

#checkpointObject



32
33
34
35
# File 'lib/jkr/cpu_usage.rb', line 32

def checkpoint
  @checkpoint2 = @checkpoint1
  @checkpoint1 = self.read_stat
end

#checkpoint_and_get_usageObject



41
42
43
44
# File 'lib/jkr/cpu_usage.rb', line 41

def checkpoint_and_get_usage
  self.checkpoint
  self.get_last_usage
end

#get_last_usageObject



54
55
56
57
58
59
60
# File 'lib/jkr/cpu_usage.rb', line 54

def get_last_usage
  unless @checkpoint1 && @checkpoint2
    raise RuntimeError.new("At least two checkpoints are required")
  end

  self.calc_usage(@checkpoint2[:system], @checkpoint1[:system])
end

#get_usageObject



46
47
48
49
50
51
52
# File 'lib/jkr/cpu_usage.rb', line 46

def get_usage
  unless @checkpoint1
    raise RuntimeError.new("Checkpointing is required")
  end

  self.calc_usage(self.read_stat[:system], @checkpoint1[:system])
end

#read_statObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/jkr/cpu_usage.rb', line 11

def read_stat
  stat_str = `cat /proc/stat`
  cpu_total = nil
  cpus = Array.new
  stat_str.each_line do |line|
    case line
    when /cpu (.*)$/
      user, nice, sys, idle, *rest = $~[1].strip.split.map(&:to_i)
      rest = rest.inject(&:+)
      cpu_total = {:user => user, :sys => sys, :nice => nice, :idle => idle, :rest => rest}
    when /cpu(\d+) (.*)$/
      idx = $~[1].to_i
      user, nice, sys, idle, *rest = $~[2].strip.split.map(&:to_i)
      cpus[idx] = {:user => user, :sys => sys, :nice => nice, :idle => idle, :rest => rest}
    end
  end

  {:system => cpu_total,
    :cpus => cpus}
end

#resetObject



37
38
39
# File 'lib/jkr/cpu_usage.rb', line 37

def reset
  @checkpoint2 = @checkpoint1 = nil
end