Okay well I pulled the calculation stuff from the procps (top) source code, and knowing absolutely no C at all
I'm not to certain that I interpreted it right, the code seems to work though, but feels like a cheap hack especially
with sleep(). So any suggestions on how to improve this would be greatly appreciated.
#!/usr/bin/perl -w use strict; sub cpu_stat { my($cpu_user, $cpu_nice, $cpu_total, $cpu_idle); open STAT_FILE, "/proc/stat" or warn "Couldn't open /proc/stat: $! +\n"; while (<STAT_FILE>) { ($cpu_user, $cpu_nice, $cpu_total, $cpu_idle) = ($1,$2,$3,$4) +if /^cpu\s+(\d+)\ (\d+) (\d+) (\d+)/; last; } close STAT_FILE; return($cpu_user, $cpu_nice, $cpu_total, $cpu_idle); } my($cpu_user_old, $cpu_nice_old, $cpu_total_old, $cpu_idle_old) = cpu_ +stat(); sleep(1); my($cpu_user, $cpu_nice, $cpu_total, $cpu_idle) = cpu_stat(); my $ticks_past = ($cpu_user + $cpu_nice + $cpu_total + $cpu_idle) - ($ +cpu_user_old + $cpu_nice_old + $cpu_total_old + $cpu_idle_old); my $scale = 100.0 / $ticks_past; $cpu_user = sprintf "%.0f", ($cpu_user - $cpu_user_old) * $scale; $cpu_nice = sprintf "%.0f", ($cpu_nice - $cpu_nice_old) * $scale; $cpu_total = sprintf "%.0f", ($cpu_total - $cpu_total_old) * $scale; $cpu_idle = sprintf "%.0f", ($cpu_idle - $cpu_idle_old) * $scale; print "user: $cpu_user%, nice: $cpu_nice%, total: $cpu_total%, idle: +$cpu_idle%\n";

Edit Masem 2001-11-04 - CODE tags


In reply to suggestions for improvement by rendler

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.