http://qs1969.pair.com?node_id=11141560

rsFalse has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

Today I tried to optimize slowest part of my program. That is inside of nested loops:
#!/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";
I changed the HOT-SPOT lines to:
( $sums[ $j - $i ] += $_[ $j ] ) > $max and $max = $sums[ $j - + $i ];
...and my code started to work ~30 percent faster. I think it is good increase in performance but a slight decrease in readability.

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?