#!/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% --