the results:#!/usr/bin/perl use Benchmark qw(cmpthese); use List::Util qw(reduce); use Inline 'C'; cmpthese (-5, { 'initial' => sub { my @numbers = (2,3,4,5); my $total = 1; for(@numbers){ $total = ($total * $_); } }, 'listutil' => sub { my @numbers = (2,3,4,5); reduce{ $a*=$b } @numbers; }, 'eval' => sub { my @numbers = (2,3,4,5); eval join "*", @numbers; }, '*=' => sub { my @numbers = (2,3,4,5); my $total=1; $total *= $_ for @numbers; }, 'reducing' => sub { my @numbers = (2,3,4,5); $numbers[0] *= pop @numbers while ( @numbers > 1 ); }, 'inline' => sub { my @numbers = (2,3,4,5); multiply( \@numbers ); } }); __DATA__ __C__ double multiply (SV * terms) { I32 numterms = 0; double res = 1.0; int i; if ((!SvROK(terms)) || (SvTYPE(SvRV(terms)) != SVt_PVAV) || ((numterms = av_len((AV *)SvRV(terms))) < 0)) { return 0; } for (i = 0; i <= numterms; i++) { res *= SvNV(* av_fetch((AV *)SvRV(terms), i, 0)); } return res; }
If I'm doing something wrong here, please correct me.Rate eval reducing initial *= listutil inline eval 21683/s -- -84% -84% -85% -85% -89% reducing 134819/s 522% -- -4% -6% -7% -31% initial 139854/s 545% 4% -- -3% -4% -28% *= 144019/s 564% 7% 3% -- -1% -26% listutil 145100/s 569% 8% 4% 1% -- -25% inline 194405/s 797% 44% 39% 35% 34% --
In reply to Re: Multiplying together the numers in an array
by eXile
in thread Multiplying together the numers in an array
by Cody Pendant
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |