Move to Apache License
[amazing.git] / lib / amazing / widgets / cpu_usage.rb
blobfa5e4ef1bb50855284c3cbb59baf3f11336c31dc
1 # Copyright 2008 Dag Odenhall <dag.odenhall@gmail.com>
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 #    http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 require 'amazing/widget'
17 module Amazing
18   module Widgets
19     class CpuUsage < Widget
20       description "CPU usage"
21       option :cpu, "CPU number, 0 is all", 0
22       field :usage, "Percent of CPU in use", []
23       default { @usage[@cpu].to_i }
25       init do
26         first = gather_data()
27         sleep 1
28         second = gather_data()
29         first.each_index do |cpunum|
30           idle = second[cpunum][3].to_i - first[cpunum][3].to_i
31           sum = second[cpunum][0..5].inject {|a,b| a.to_i + b.to_i } -
32             first[cpunum][0..5].inject {|a,b| a.to_i + b.to_i }
33           @usage[cpunum] = 100 - (idle * 100) / sum.to_f
34         end
35       end
37       private
39       def gather_data
40         cpus = []
41         ::File.readlines("/proc/stat").select {|l| l =~ /^cpu/ }.each do |l|
42           l = l.split
43           cpunum = l[0] == "cpu" ? 0 : l[0].scan(/\d+/)[0].to_i + 1
44           cpus[cpunum] = l[1..-1]
45         end
46         cpus
47       end
48     end
49   end
50 end