Created
September 3, 2009 05:14
-
-
Save hitode909/180139 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# -*- coding: utf-8 -*- | |
require "webrick" | |
require "inline" | |
require "ruby-growl" | |
class Numeric | |
def near?(with) | |
(self - with).abs < 10 | |
end | |
end | |
class Array | |
def average | |
self.size > 0 ? self.inject{ |a,b| a+b } / self.size : 0 | |
end | |
end | |
module Processor | |
class << self | |
# http://d.hatena.ne.jp/harukasan/20080825#1219609683 | |
inline do |builder| | |
builder.include '<mach/host_info.h>' | |
builder.include '<mach/processor_info.h>' | |
builder.c <<-EOF | |
double usage(void) { | |
mach_port_t host_port; | |
host_cpu_load_info_data_t prev_cpu_load, cpu_load; | |
mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT; | |
natural_t user, system, idle; | |
double usage; | |
host_port = mach_host_self(); | |
host_statistics(host_port, HOST_CPU_LOAD_INFO, (host_info_t)&prev_cpu_load, &count); | |
sleep(1); | |
host_statistics(host_port, HOST_CPU_LOAD_INFO, (host_info_t)&cpu_load, &count); | |
user = cpu_load.cpu_ticks[CPU_STATE_USER] - prev_cpu_load.cpu_ticks[CPU_STATE_USER]; | |
system = cpu_load.cpu_ticks[CPU_STATE_SYSTEM] - prev_cpu_load.cpu_ticks[CPU_STATE_SYSTEM]; | |
idle = cpu_load.cpu_ticks[CPU_STATE_IDLE] - prev_cpu_load.cpu_ticks[CPU_STATE_IDLE]; | |
usage = (double)(user + system) / (system + user + idle) * 100.0; | |
return usage; | |
} | |
EOF | |
end | |
end | |
end | |
history = [] | |
about = Processor.usage | |
growl = Growl.new "127.0.0.1", "cpu-usage", ["message"] | |
WEBrick::Daemon.start do | |
loop do | |
history << Processor.usage | |
history.shift if history.size > 4 | |
average = history.average | |
if not average.near? about | |
growl.notify "message", "CPU Usage", | |
"%.1f%% (#{"+" if history.average > about}%.1f)" % [average, average - about] | |
about = average | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment