Perl multiplication vs. division Benchmark

Today I want to compare the multiplication and division operation in Perl both could do the same, as example “100*2” is the same as “100/0.5”. And “100*0,5” is the same as “100/2”. Now let’s see what’s the Benchmark says:

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

my $x = 100;
my $y = 0;

cmpthese(-1, {
'div'  => sub {$y = $x/2},
'mul'  => sub {$y = $x*0.5},
});

cmpthese(-1, {
'div'  => sub {$y = $x/0.5},
'mul'  => sub {$y = $x*2},
});

We see in bout cases the multiplication is much faster:

          Rate  div  mul
div 14234063/s   -- -48%
mul 27235740/s  91%   --
          Rate  div  mul
div 16834936/s   -- -28%
mul 23301688/s  38%   --

To change the divisor to a factor calculate : factor = 1/divisor.This could be also useful if you have the same divisor for some calculations.

One thought on “Perl multiplication vs. division Benchmark”

Leave a Reply

Your email address will not be published.

15 + ten =