in reply to Help w/ Code Optimization

You might also try this :

It

(I'm sure your numerous tests will make it sure ;-)

gives as result :

Benchmark: timing 10 iterations of Root, Root2...

~~
~~

Corrected my code! I misplaced the $t calculation outside the loop,

which is wrong beccause $guess change inside the loop.

As you can see it's no more so fast...

"

sub Root2 { my $num = shift; my $root = shift; my $iterations = shift || 10; if ( $root == 0 ) { return 1 } if ( $num < 0 ) { return undef } my $current = Math::BigFloat->new(); my $guess = Math::BigFloat->new( $num / $root ); my $t=Math::BigFloat->new($guess**($root-1)); 1st version : WRONG ! sh +ould be in the loop. for ( 1 .. $iterations ) { $current = $guess - ( $guess * $t - $num ) / ( $root * $t ); if ( $guess eq $current ) { last } $t=Math::BigFloat->new($current**($root-1)); $guess = $current; } return $current; }

**The idea behind, is that '**' is MUCH slower than '*', so I exchange 2 '**' for one '**' and 2 '*'**It

__seems__indeed to speed things alot :(I'm sure your numerous tests will make it sure ;-)

timethese(10,{ 'Root'=> sub {Root(1000,60)}, 'Root2'=> sub {Root2(1000,60)}});

gives as result :

Benchmark: timing 10 iterations of Root, Root2...

**Root**: 104 wallclock secs (104.38 usr + 0.01 sys = 104.39 CPU) @**0.10/s**(n=10)**Root2**: 15 wallclock secs (14.75 usr + 0.00 sys = 14.75 CPU) @

**0.68/s**(n=10)

**Root2:**97 wallclock secs (92.67 usr + 0.16 sys = 92.83 CPU) @**0.11/s**(n=10)**UPDATE :**Corrected my code! I misplaced the $t calculation outside the loop,

which is wrong beccause $guess change inside the loop.

As you can see it's no more so fast...

"

**O**nly**B**ad**C**oders**C**ode**B**adly**I**n**P**erl" (OBC2BIP)
In Section
Seekers of Perl Wisdom