Skip to content

Instantly share code, notes, and snippets.

@ken39arg
Created May 14, 2013 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ken39arg/5573883 to your computer and use it in GitHub Desktop.
Save ken39arg/5573883 to your computer and use it in GitHub Desktop.
use strict;
use warnings;
use 5.010;
use Benchmark qw/timethese cmpthese/;
sub action_a {
my ($a, $b) = @_;
$b ||= 0;
return $a + $b;
}
sub action_b {
my ($a, $b) = @_;
$b ||= 0;
return $a - $b;
}
sub action_c {
my ($a, $b) = @_;
$b ||= 0;
return $a * $b;
}
sub action_d {
my ($a, $b) = @_;
$b ||= 1;
return $a / $b;
}
sub param {
#return 3, 10, 2;
return (
int(rand(5)),
rand(100000),
rand(100) + 1
);
}
sub putturn_if {
my ($act, $a, $b) = @_;
if ($act == 1) {
action_a($a, $b);
} elsif ($act == 2) {
action_b($a, $b);
} elsif ($act == 3) {
action_c($a, $b);
} elsif ($act == 4) {
action_d($a, $b);
} else {
return 0;
}
}
sub putturn_given {
my ($act, $a, $b) = @_;
given ($act) {
when (1) { return action_a($a, $b) }
when (2) { return action_b($a, $b) }
when (3) { return action_c($a, $b) }
when (4) { return action_d($a, $b) }
default { return 0 }
}
}
my $acts = {
1 => *action_a,
2 => *action_b,
3 => *action_c,
4 => *action_d,
};
sub putturn_hash {
my ($act, $a, $b) = @_;
if ($acts->{$act}) {
$acts->{$act}->($a, $b);
} else {
return 0;
}
}
my $result = timethese(1000000, {
if => sub {
putturn_if(param());
},
given => sub {
putturn_given(param());
},
hash => sub {
putturn_hash(param());
},
});
cmpthese $result;
__END__
Benchmark: timing 1000000 iterations of given, hash, if...
given: 5 wallclock secs ( 4.37 usr + 0.01 sys = 4.38 CPU) @ 228310.50/s (n=1000000)
hash: 3 wallclock secs ( 3.35 usr + 0.01 sys = 3.36 CPU) @ 297619.05/s (n=1000000)
if: 4 wallclock secs ( 3.34 usr + 0.00 sys = 3.34 CPU) @ 299401.20/s (n=1000000)
Rate given hash if
given 228311/s -- -23% -24%
hash 297619/s 30% -- -1%
if 299401/s 31% 1% --
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment