[Israel.pm] Rounding benchmark

Jason Elbaum Jason.Elbaum at freescale.com
Thu May 6 07:57:39 PDT 2004


A simple benchmark of rounding to two decimal places. The code compares 
the mathematical solution with the sprintf solution by generating an 
array of random numbers, rounding them to two decimal places, and 
summing them.

My results in seconds (YMMV):

             math    1.79
             text    4.14

The sprintf() solution is over twice as slow on my system.

The code:


use strict;

use constant SIZE => 100000;

my %testsubs = (
	math => sub {
	  return int($_[0]*100 + 0.5) / 100;
	},

	text => sub {
	  return sprintf("%.2f", $_[0]);
	},
);

my %result;

while (my ($subname, $routine) = each %testsubs) {
   timeit($subname, $routine, \%result);
}

foreach my $subname (sort keys %result) {
   printf "%16s", $subname;
   printf("%8.2f", $result{$subname});
   print "\n";
}

sub timeit {
   my ($subname, $routine, $result) = @_;

   my ($su,$ss) = times;

   my @vals;

   for(1 .. SIZE) {
     my $val = rand(1000);

     push @vals, &$routine($val);
   }

   my $sum = 0;
   foreach (@vals) {
     $sum += $_;
   }
   my ($eu,$es) = times;
   my ($tu,$ts) = ($eu-$su,$es-$ss);
   my $total = $tu + $ts;

   $result->{$subname} = $total;
}



More information about the Perl mailing list