CPU utilization from /proc/stat

kdl: There is script for getting CPU utilization from /proc/stat in Linux here. Maybe somebody find it useful.

set STAT_FILE "/proc/stat"
set INTERVAL 1000

proc get_cpu_list {} {
    set fd [open $::STAT_FILE]
    set start 0

    while {[gets $fd data] >=0 && [regexp {(cpu\d*)\s+(.*)} $data -> name times]} {
        lappend cpu_list $name [split $times " "]
    }

    close $fd
    return $cpu_list
}

proc calc_usage {old_times new_times} {
    foreach {cpu times} $old_times {
        set idle($cpu) [lindex $times 3]
        foreach time $times {
            incr busy($cpu) $time
        }
        set busy($cpu) [expr {$busy($cpu) - $idle($cpu)}]
    }

    foreach {cpu times} $new_times {
        set busy($cpu) [expr {-$busy($cpu) - [lindex $times 3]}]
        set idle($cpu) [expr {[lindex $times 3] - $idle($cpu)}]
        foreach time $times {
            incr busy($cpu) $time
        }

        if {$busy($cpu) + $idle($cpu)} {
            lappend list_usage $cpu [expr { 100 * $busy($cpu) / ($busy($cpu) + $idle($cpu))}]
        } else {
            lappend list_usage $cpu 0
        }
    }

    return $list_usage
}

proc timer {old_times} {
    set new_times [get_cpu_list]
    puts [calc_usage $old_times $new_times]
    after $::INTERVAL [list timer $new_times]
}

timer [get_cpu_list]
vwait forever