Friday, 28 September 2012

Benchmarking Perl functions

 Benchmark is outstanding for comparing performance of perl functions.

#!/usr/bin/perl
use Benchmark qw(:all) ;

cmpthese(10000, {
        'Trial 1' => sub{
                my $i=0;
                for(my $j=1; $j<100; $j++){
                        $i=$j;
                }
        },

        'Trial 2' => sub{
                my $i=99;
        },

});

print "Done\n";




Gives output:

          Rate Trial 1 Trial 2
Trial 1  977/s      --    -86%
Trial 2 6803/s    597%      --
Done



Through this I was able to determine that for high speed use you shouldn't bother testing the existence of a key in a hash table.

I was also able to determine that nested ifs are better than multiple conditions in a single if.

I.e.
if(A && B && C && D){
}
is worse than
if(A){
  if(B){
    if(C){
      if(D){
      }
    }
  }
}



*best not doing this in an Amazon ec2 micro instance as repeated tests may put a limit on CPU usage and skew results*

No comments:

Post a Comment