Microsoft
Software
Hardware
Network
Question : Perl script taking too long
I have a script that does a lot of sorting based upon a 'simple moving average' which in turn is based upon 100's of arrays. The program is spending a lot of time performing the math. I must speed it up. Here is the code:
------------------
package MAIN;
use strict;
sub simple_moving_avg;
my $length_of_sma = 4;
my @price_array = qw /
11.3
11.25
11.82
11.64
11.19
11.48
11.37
10.84
10.51
10.76
10.8
11.25
11.36
11.34
11.59
11.41
11.18
11.11
11.72
11.57
/;
foreach my $i (@price_array) {
print "i: $i\n";
}
my $sma = 0;
for (my $count = 100000; $count >= 1; $count--) { # pops of 4 values "$length_ma"
$sma = simple_moving_avg(\@price_
array,$len
gth_of_sma
);
}
print "Simple moving avg: $sma\n";
exit;
sub simple_moving_avg {
my $pointer_array = $_[0];
my $length_ma = $_[1];
my $sum = 0;
my @tmp = @$pointer_array;
for (my $count = $length_ma; $count >= 1; $count--) {
my $value = pop (@tmp);
if (defined $value) {
$sum = $value + $sum;
}
}
my $ma = sprintf("%.2f",($sum / $length_ma));
return $ma;
}
--------------------------
Here is the result from running DProf:
Total Elapsed Time = 1.987965 Seconds
User+System Time = 2.194965 Seconds
Exclusive Times
%Time ExclSec CumulS #Calls sec/call Csec/c Name
108. 2.377 2.377 100000 0.0000 0.0000 MAIN::simple_moving_avg
0.00 - -0.000 1 - - strict::import
0.00 - -0.000 1 - - main::BEGIN
0.00 - -0.000 1 - - strict::bits
0.00 - -0.000 1 - - MAIN::BEGIN
--------
My question is: Can this perl subroutine be improved upon (the ExclSec needs to be cut by at least 50%)? I am unable to modify the array being passed into the sub. If the code can not be significantly improved upon would it be faster to call a C++ program (I am learning C++) or assembler? What would that code be? Many thanks.
Answer : Perl script taking too long
sub simple_moving_avg{
my ($pointer_array,$length_ma
)=@_;
my $sum = 0;
$sum += $_ for @{$pointer_array}[0..$leng
th_ma-1];
return sprintf"%.2f",$sum / $length_ma;
}
Random Solutions
Callback function in class
How can i get programs/folders to open with left click, in Vista?
Why isnt Access used in larger co's
How do I get a static value list to show when I have a parameter prompt another parameter?
string manipulation
Nokia E72 DNS Problem
word press password??
RPD to W2K3 SP2 failing - RPC server unavailable
text to at&t cell phone from web
How can I get WIndows Fax And Scan to resend to busy numbers?