Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Hi all, The snippet of code below is taking some time in doing what it does (computes min, max and means of several arrays). Is there a way to speed up the process? Thanks, Stacy. foreach $checked (@avail) { chomp($checked); if ( $checked =~ /\.gz$/ ) { open(LOG, "/usr/local/gnu/bin/gunzip -c < $checked |") or die "$checked open failed: $!\n"; } else { open(LOG, "<$checked") or die "$checked open failed: $!\n"; } #reset data structures $MaxWSpd = $AvgWSpd = $WindDir = $OutTemp = 0; @maxwspd = (); @avgwspd = (); @outtemp = (); @winddir = (); while ($line = <LOG>) { %months = qw{JAN 1 FEB 2 MAR 3 APR 4 MAY 5 JUN 6 JUL 7 AUG 8 SEP 9 OCT 10 NOV 11 DEC 12}; next if $line =~ /^\D/; #Skip header next if $line =~ /9999/; #Skip bad records ($Date,$MaxWSpd,$AvgWSpd,$WindDir,$OutTemp) = (split(" ",$line)) +[0,2,3,4,8]; next if $MaxWSpd < 0; next if $AvgWSpd < 0; next if $WindDir < 0; next if $OutTemp < 0; ($day,$month,$year) = split('-',$Date); $month = sprintf "%02d", $months{$month}; if ($WindDir > 360) { $WindDir = $WindDir%360 } push (@maxwspd,$MaxWSpd); push (@avgwspd,$AvgWSpd); push (@outtemp,$OutTemp); push (@winddir,$WindDir); } #end of while $MeanAvg = sprintf("%4.1f", mean(\@avgwspd)); $MeanWDir = sprintf("%4.1f", mean(\@winddir)); $MaxWSpd = sprintf("%4.1f", max(\@maxwspd)); $MinWSpd = sprintf("%4.1f", min(\@maxwspd)); $MaxOutTemp = sprintf("%4.1f", max(\@outtemp)); $MinOutTemp = sprintf("%4.1f", min(\@outtemp)); push(@stats, "$year/$month/$day: $MinWSpd:$MaxWSpd $MeanAvg $MeanWDir $MinOutT +emp:$MaxOutTemp"); close(LOG); } #end of foreach foreach (@stats) { print $_, "\n"; } #-------------------- sub mean { my ($arrayref) = @_; my $result; foreach (@$arrayref) { $result += $_; } return $result / @$arrayref; } #-------------------- sub max { my ($arrayref) = @_; $max = -10; foreach (@$arrayref) { if ($_ > $max) { $max = $_ } } return $max; } #-------------------- sub min { my ($arrayref) = @_; $min = 50; foreach (@$arrayref) { if ($_ < $min) { $min = $_ } } return $min; } #--------------------
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Inefficient code?
by Masem (Monsignor) on Apr 22, 2001 at 15:18 UTC | |
|
(ar0n: use List::Util) Re: Inefficient code?
by ar0n (Priest) on Apr 22, 2001 at 18:34 UTC | |
|
Re: Inefficient code?
by Albannach (Monsignor) on Apr 22, 2001 at 16:45 UTC | |
|
Re: Inefficient code?
by RhetTbull (Curate) on Apr 23, 2001 at 05:22 UTC | |
by Anonymous Monk on Apr 23, 2001 at 10:42 UTC |