in reply to how to multiply an array of number as fast as posible
For this operation, one very simple optimization would be swapping from a for to a while loop since Foreach Loops need to construct the list before beginning iteration. threads is also a fairly simple way to improve performance. Here is a simple benchmark, showing a 38% speedup using a while loop and two threads. Note the speedup is not higher because creating threads involves overhead.
Threading in this case does not make sense - the overhead in starting a thread exceeds the performance boost. For loops with range operators are automatically transformed into efficient C-style loops internally by Perl. But you should really be using the Stirling_approximation and only storing the log of your value to avoid overflow.
#!/usr/bin/perl use strict; use warnings; use Benchmark qw':all :hireswallclock'; use threads; cmpthese(10, { 'while' => sub { my $i = 230000; my $k = 1; while ($i <= 900000) { $k *= $i++; } }, 'for' => sub { my $k = 1; for (230000 .. 900000) { $k *= $_; } }, 'threads' => sub { my $k = 1; my $thr2 = async { my $k = 1; my $i = 565001; while ($i <= 900000) { $k *= $i++; } }; my $i = 230000; while ($i <= 565000) { $k *= $i++; } $k *= $thr2->join(); } });
outputs
Rate threads while for threads 3.09/s -- -29% -38% while 4.33/s 40% -- -13% for 4.96/s 60% 15% --
And if you look at the results from these multiplications, you have likely exceeded the maximum value representable by floating point on your machine.
Update: Need caffeine, read my Benchmark results backwards, fixed above.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: how to multiply an array of number as fast as posible
by BrowserUk (Patriarch) on Sep 02, 2010 at 17:04 UTC | |
by kennethk (Abbot) on Sep 02, 2010 at 17:32 UTC | |
by BrowserUk (Patriarch) on Sep 02, 2010 at 17:56 UTC | |
|
Re^2: how to multiply an array of number as fast as posible
by ikegami (Patriarch) on Sep 02, 2010 at 15:28 UTC | |
by kennethk (Abbot) on Sep 02, 2010 at 16:15 UTC | |
by BrowserUk (Patriarch) on Sep 02, 2010 at 16:40 UTC | |
by ikegami (Patriarch) on Sep 02, 2010 at 16:47 UTC | |
by BrowserUk (Patriarch) on Sep 02, 2010 at 17:07 UTC |