in reply to suggestions for improvement
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: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);
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...)my %hash; @hash{qw/ user nice total idle /} = cpu_stat(); print "nice: $hash{nice}\n";
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...
|
|---|