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'
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 }
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
41 ::File.readlines("/proc/stat").select {|l| l =~ /^cpu/ }.each do |l|
43 cpunum = l[0] == "cpu" ? 0 : l[0].scan(/\d+/)[0].to_i + 1
44 cpus[cpunum] = l[1..-1]