Class: CPU::UsageSampler

Inherits:
Object
  • Object
show all
Defined in:
lib/cpu/usage_sampler.rb

Constant Summary collapse

CPU =

This regular expression is used to parse cpu times from the /proc/stat kernel file.

/^cpu(\d+)#{'\s+(\d+)' * 4}/
USER_HZ =

This value is used to convert cpu times from jiffies into seconds.

100

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeUsageSampler

Creates a new UsageSampler instance.



4
5
6
# File 'lib/cpu/usage_sampler.rb', line 4

def initialize
  sample
end

Instance Attribute Details

#usagesObject (readonly)

Return all CPU::Usage instances stored in this UsageSampler, if any.



9
10
11
# File 'lib/cpu/usage_sampler.rb', line 9

def usages
  @usages
end

Instance Method Details

#sampleObject

Take one sample of CPU usage data for every processor in this computer and store them in the usages attribute.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/cpu/usage_sampler.rb', line 26

def sample
  total, @usages = nil, {}
  timestamp = Time.now
  File.foreach('/proc/stat') do |line|
    case line
    when /^cpu[^\d]/
      next
    when CPU
      times = $~.captures
      processor_id = times[0] = times[0].to_i
      (1...times.size).each { |i| times[i] = times[i].to_f / USER_HZ }
      times << timestamp << timestamp
      @usages[processor_id] = Usage.new(self, *times)
    else
      break
    end
  end
  if @usages.empty?
    raise NoSampleDataError, "could not sample measurement data"
  end
  self
end

#sum_usagesObject

Returns a CPU::Usage instance, that sums up all CPU::Usage instances for all processors in this computer.



13
14
15
# File 'lib/cpu/usage_sampler.rb', line 13

def sum_usages
  @usages and @usages.values.inject(&:+)
end