Sha256: 33b2047babe2312d134bee7a78c3c5fd97948fe0380c4fb30bed6f986eace28a

Contents?: true

Size: 786 Bytes

Versions: 4

Compression:

Stored size: 786 Bytes

Contents

module ServState
  class CpuUsage

    attr_reader :usage

    def update
      usage, total = proc_stat_values

      usage_diff = usage - @old[:cpu_usage]
      total_diff = total - @old[:cpu_usage_total]

      @old[:cpu_usage]       = usage
      @old[:cpu_usage_total] = total

      @usage = ((usage_diff / total_diff.to_f) * 100).to_i
    end

  private

    def initialize
      @old = Hash.new
      @old[:cpu_usage], @old[:cpu_usage_total] = proc_stat_values
      @usage = 0
      sleep 1
    end

    def proc_stat_values
      stat_line   = IO.readlines('/proc/stat').grep(/^cpu /).first.split
      stat_values = stat_line.map{ |element| element.to_i }
      total = stat_values.inject(:+)
      usage = stat_values[1..3].inject(:+)
      [usage, total]
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
ServState-0.1.3 lib/ServState/cpu_usage.rb
ServState-0.1.2 lib/ServState/cpu_usage.rb
ServState-0.1.1 lib/ServState/cpu_usage.rb
ServState-0.1.0 lib/ServState/cpu_usage.rb