perlquestion
rsFalse
Hello,<br><br>
Today I tried to optimize slowest part of my program. That is inside of nested loops:
<code>
#!/usr/bin/perl
use warnings;
use strict;
$\ = $/;
srand( 1 );
my $n = 2e3;
@_ = map int rand 1e5, 1 .. $n;
print "@_[ 0 .. 3 ] ...";
my @max;
push @max, ( sort { $b <=> $a } @_ )[ 0 ];
my @sums = @_;
for my $i ( 1 .. $n - 1 ){
my $max = -~0;
for my $j ( $i .. $n - 1 ){
# HOT-SPOT {
$sums[ $j - $i ] += $_[ $j ];
$sums[ $j - $i ] > $max and $max = $sums[ $j - $i ];
# HOT-SPOT }
}
push @max, $max;
}
print "Finished";
</code>
I changed the HOT-SPOT lines to:
<code>
( $sums[ $j - $i ] += $_[ $j ] ) > $max and $max = $sums[ $j - $i ];
</code>
...and my code started to work ~30 percent faster. I think it is good increase in performance but a slight decrease in readability.<br><br>
I executed these code dozens of times to see how fast do they work. I observed that both programs work in not constant time and about every 10th run program occasionally consume >1.5x time than usually. I observed it on perl v5.30 and v5.32, but not on v5.14. Any ideas why every ~10th run any of these programs runs much slower?