On 26/05/2011 06:18, Uri Guttman wrote:
>>>>>> "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 )

It is also rare to need access to the array index (even if you think you
do!). Perl is much more in its element if you loop over the elements of
an array instead of its indices:

  foreach my $elem (@lines) {
    :
  }

Later on you publish this code, which uses a slice in this way

>  for my $i (99 .. 60000)
> {
>       my $sum;
>       map {$sum += $_->{foo_value}} @lines[$i - $n + 1 .. $i];
>       push @res, $sum;
> }

First of all, never use map in this way. It is a uniform list operator,
designed to apply the same transform to every element of its object list
and return a new list as a return value. Here you have map unnecessarily
building the new list and then then immediately discarding it. Your code
should be

 $sum += $_->{foo_value}} foreach @lines[$i - $n + 1 .. $i];

or, to demonstrate my point about map

  $sum += $_ foreach map $_->{foo_value}, @lines[$i - $n + 1 .. $i];

This last line maps the elements in the slice of @lines to a list of
their {foo_value} structure elements, and accumulates those into $sum.

I am sure that you could get your C program working with acceptable
speed, but you would need to write in Perl idioms rather than simply
transliterate the C code.

I would warn against writing 'C in Perl' together with embedded C, as it
makes the program far less maintainable. As you have not described the
purpose of your work, I guess that improved maintainability or
cross-platform functionality are amongst your goals?

Please persevere. Perl can be very fast, I assure you.

Rob


-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to