A word on relative efficiencies of the two formulae listed below... I ran timethese/cmpthese on the two, using a half-million iterations, ten times. The "folded" formula came out faster six times, at an average of 8.67% faster, while the long form won the race four times, but with an average of 12.25% faster.
I leave it to the statisticians out there to sort out the meaning of these figures, and I've appended the script used for those interested in playing about any further.
********************************* code ***********************************
#! /usr/local/bin/perl
use strict;
use warnings;
use Benchmark qw(timethese cmpthese);
my ($A, $B, $C, $D) = (10, 21, 11, 6);
my $sum;
my $r = timethese( 500_000, {
'long test' => sub {
$sum = (256*256*256*$A) + (256*256*$B) + (256*$C) + $D;
},
'short test' => sub {
$sum = (($A*256+$B) * 256 + $C) * 256 + $D;
}
} );
cmpthese( $r );
********************************* code ***********************************
| David Nicol <[EMAIL PROTECTED]>
Sent by: [EMAIL PROTECTED] 11/10/2005 12:47
|
To: "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> cc: "[email protected]" <[email protected]> Subject: Re: Matching ip to Network |
On 11/10/05, David Budd <[EMAIL PROTECTED]> wrote:
> > Raniak Robert is right.
> > I did mistake in formulation. Right one is
> > (256*256*256*A)+(256*256*B)+(256*C)+D
>
> I've always done ((A*256+B)*256+C)*256+D
> Slightly more efficient
is not. They both have three multiplications and three adds,
after the constants have been folded. You could do it with
bitshifting instead of math if you want, and it you're
afraid of endianness problems with
pack('C4',split /\./,$ip)
(A<<24)|(B<<16)|(C<<8)|D
There was a perl6 proposal once to add the math concept of interval
to regular _expression_ language, but it didn't get much traction.
--
David L Nicol
A room without books is perfect for watching television
_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
_______________________________________________ ActivePerl mailing list [email protected] To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
