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
Demoted windows 2003 domain controller log on
How can I determine if winlogon.exe is malware?
Refresh key for excel formulas linked to other sheets?
Make Table Query that searches for records that are NOT located in two tables.
How do we install snmp on Mac OS-X 10.3 ??
Simple 3 column <li>, middle column stretches?
Cisco ME 6500 Ios update
exchange 2010 storage
Create row based view from several tables.
sed/awk help