>>>>> "XL" == Xi Liu <jason.li...@gmail.com> writes:
XL> I translated a program from c to perl.but the perl program cost 15 seconds XL> compare to the original c one cost only less than 1 second, I guess this XL> might be the result of I literally translated the program, using a lot of XL> array subscripts. After I profile the perl program, it turned out my guess XL> was true. you need to learn real perl first and not code as in c. this is true for most langs. each has idioms that work best and literal translations from one to another are almost always bad. XL> for($i = 0; $i < @lines; $i++) first rule: don't use c style index loops when you can avoid them. that line is much faster and more perlish as: foreach my $i ( 0 .. $#lines ) XL> $sum += $lines[$_]->{foo_value} for ($i - $n + 1 .. $i); XL> sorry I can't post the whole code, but the lines above is the big XL> framework, I also omit all the boundary check. "$sum += XL> $lines[$_]->{foo_value} for ($i - $n2 + 1 .. $i)" this line XL> consumes all the time. XL> I got a array, for each element of the array I have to sum up the XL> $n elements prior to the current one. I know I should use pop push XL> shift unshift all the perl list operators instead of subscripting, XL> but I just don't know how, would somebody tell me what is the perl XL> way of doing this? that doesn't seem to be what the code is doing. $sum isn't just a sum, it is a sum of sums as you have a two dimensional loop. did you translate the code incorrectly or can you more clearly specify what is being summed here? you can get speedups in other ways too. you can do a map or slice of the array and call sum (in List::Util) on that list. it will be much faster than the += loop you have there. also you are accessing {foo_value} over and over for each line (since the loop is 2 levels deep). a better algorithm would do a sum of sums where you sum one set and then add that to the next set. i won't get into that since the second loop logic isn't clear to me (which set of elements are being summed and resummed). that is more your problem. but this can be sped up a great deal with better coding. uri -- Uri Guttman ------ u...@stemsystems.com -------- http://www.sysarch.com -- ----- Perl Code Review , Architecture, Development, Training, Support ------ --------- Gourmet Hot Cocoa Mix ---- http://bestfriendscocoa.com --------- -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/