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?
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.