use List::Util 'sum'; # might be overkill sub cpu_stat { open(STAT_FILE, "< /proc/stat") or warn "/proc/stat: $!"; my $line = <STAT_FILE>; close(STAT_FILE); $line =~ /^cpu\s+(\d+) (\d+) (\d+) (\d+)/; } my @before = cpu_stat(); sleep 1; my @after = cpu_stat(); my $ticks_past = sum(@after) - sum(@before); my $scale = 100 / $ticks_past if $ticks_past; # divide by zero error # Arguably, this is less readable than your code printf("user: %d%%, nice: %d%%, total: %d%%, idle: %d%%\n", map { ($after[$_] - $before[$_]) * $scale } 0 .. 3);
There is benefit, though, of using those temporary variables in cases where you want to do additional operations to them. Working with them in array form is not very readable. A hash is another option:
my %hash; @hash{qw/ user nice total idle /} = cpu_stat(); print "nice: $hash{nice}\n";
A lot of this, though, is just personal style. You're doing these once a second, so it's not like you're coding yourself into a hugely inefficient corner here. Use whatever method maximizes readability and maintainability for you. There was nothing really wrong with your code from an efficiency point of view, and it was very readable. (Though I'm still trying to figure out if that's the way you want to calculate $scale...)

Why were you concerned about doing the sleep? Any implementation that tries to keep real-time tabs on CPU statistics has to do it in a polling style, which is what this is. If you do it much faster than that, your monitoring process is going to end up using 100% of the very CPU you're trying to keep tabs on!

Hope this helps...


In reply to Re: suggestions for improvement by Fastolfe
in thread 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.