in reply to Converting an array of bytes into a BigInt - speed considerations


On the assumption that a shift would be faster than a multiplication/exponentiation I tried this:
sub bytearray_to_bigint2 { my $result = Math::BigInt->new('0'); for my $byte (reverse @_) { my $tmp = Math::BigInt->new($byte); $result = $result->blsft(8); $result += $tmp; } return $result; }

This appears to be faster, see the bechmark below. The speed increases for bigger ints.

#!/usr/bin/perl -wl use strict; use Math::BigInt; use Benchmark 'cmpthese'; our $bigint; our @bytes; $bigint = Math::BigInt->new('12345678' x 10); @bytes = bigint_to_bytearray($bigint); print join ",", @bytes, "\n"; print bytearray_to_bigint(@bytes), "\n"; print bytearray_to_bigint2(@bytes), "\n"; sub bigint_to_bytearray { my $bigint = shift; my @bytes; while(1) { my ($q,$r) = $bigint->brsft(8); push(@bytes,$r+0); last if $q == 0; $bigint = Math::BigInt->new($q); } return @bytes; } ## This is the one I would like to speed up ## The array looks something like (127,6,64,27,166,33 .... ) sub bytearray_to_bigint { my @array = @_; my $count = Math::BigInt->new('0'); my $result = Math::BigInt->new('0'); foreach my $a (@array) { $result += $a * (256**$count++); } return $result; } sub bytearray_to_bigint2 { my $result = Math::BigInt->new('0'); for my $byte (reverse @_) { my $tmp = Math::BigInt->new($byte); $result = $result->blsft(8); $result += $tmp; } return $result; } cmpthese(10, { 'mult' => 'bytearray_to_bigint (@bytes)', 'shift' => 'bytearray_to_bigint2(@bytes)', }); __END__ timing 10 iterations of mult, shift ... mult: 1 wallclock secs ( 1.15 usr + 0.00 sys = 1.15 CPU) @ 8.70 +/s (n=10) shift: 1 wallclock secs ( 0.86 usr + 0.00 sys = 0.86 CPU) @ 11.63 +/s (n=10) Rate mult shift mult 8.70/s -- -25% shift 11.6/s 34% -- Here are the results for '12345678' x 100; mult: 89 wallclock secs (74.95 usr + 2.17 sys = 77.12 CPU) @ 0.13/ +s (n=10) shift: 17 wallclock secs (17.46 usr + 0.04 sys = 17.50 CPU) @ 0.57/ +s (n=10) s/iter mult shift mult 7.71 -- -77% shift 1.75 341% --

--
John.

Replies are listed 'Best First'.
Re: Re: Converting an array of bytes into a BigInt - speed considerations
by bart (Canon) on Jan 23, 2003 at 13:51 UTC
    Does it give the proper results? As in the old version I'm using, blsft() appears to return a string not a bigint object, $result += $tmp; might not do the proper thing.
    use Math::BigInt; use Data::Dumper; print Dumper +Math::BigInt->new(1)->blsft(8); print $Math::BigInt::VERSION;
    Result:
    $VAR1 = '+256'; 0.01
    OTOH, $tmp is a bigint object. Hmm...

    OK, no reason to panic:

    $result = 1; $result += new Math::BigInt('1234567890' x 10);
    does seem to work alright.

      It does give the correct results. Give me some credit. ;-)

      I've updated the above benchmark to include the test that I removed before posting.

      I'd agree that the Math::BigInt objects behave a little bit counter-intuitively.

      --
      John.