Do you know where your variables are? PerlMonks

### comment on

 Need Help??

If, based on your answers in this thread, ultimate goal is better speed after all (and not mysterious slow-downs on every 10th run, about which I have nothing to add), then as usual in case of large arrays, use PDL;. Second pair of results are for 10x \$n.

```use warnings;
use strict;

use feature 'say';
use Time::HiRes 'time';

srand( 1 );
my \$n = 2e3;
my @input = map int rand 1e5, 1 .. \$n;

my ( \$check1, \$check2 );

{                   # original code
my \$t = time;

my @max;

push @max, ( sort { \$b <=> \$a } @input )[ 0 ];
my @sums = @input;

for my \$i ( 1 .. \$n - 1 ){

my \$max = -~0;
for my \$j ( \$i .. \$n - 1 ){
# HOT-SPOT {
( \$sums[ \$j - \$i ] += \$input[ \$j ] ) > \$max
and \$max = \$sums[ \$j - \$i ];
# HOT-SPOT }
}
push @max, \$max;
}

say time - \$t;
\$check1 = pack 'I*', @max;
}

{                   # PDL
my \$t = time;

use PDL;
use PDL::NiceSlice;

my \$sums = zeroes long, scalar @input;
my \$vec  = pdl long, \@input;

my @max = map \$sums( 0 : -\$_ - 1 )
-> inplace
-> plus( \$vec( \$_ : -1 ), 0 )
-> maximum
, 0 .. \$#input;

say time - \$t;
\$check2 = pack 'I*', @max;
}

use Test::More;
is \$check1, \$check2;
done_testing;

__END__

0.148595094680786
0.0387320518493652
ok 1
1..1

14.5055229663849
0.759373903274536
ok 1
1..1
[download]```

In reply to Re: Performance issue in the loop. by vr
in thread Performance issue in the loop. by rsFalse

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

• Are you posting in the right place? Check out Where do I post X? to know for sure.
• Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
• Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
• Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
 Username: Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2023-02-03 20:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
I prefer not to run the latest version of Perl because:

Results (29 votes). Check out past polls.

Notices?