sub factorial {
my ($num) = @_;
@_ = (1, 1, $num);
goto &_factorial;
}
sub _factorial {
my ($result, $counter, $max) = @_;
return $result if $counter > $max;
@_ = (($result * $counter), ($counter + 1), $max);
goto &_factorial;
}
####
my $_factorial;
$_factorial = sub {
my ($result, $counter, $max) = @_;
return $result if $counter > $max;
@_ = (($result * $counter), ($counter + 1), $max);
goto $_factorial;
};
sub factorial {
my ($num) = @_;
@_ = (1, 1, $num);
goto $_factorial;
}
####
#!/usr/local/bin/perl
use warnings;
use strict;
use Benchmark;
use Test::More tests => 3;
my $_fact3;
$_fact3 = sub {
my ($result, $counter, $max) = @_;
return $result if $counter > $max;
@_ = (($result * $counter), ($counter + 1), $max);
goto $_fact3;
};
my $number = shift or die "No number supplied";
validate_factorial_routines($number);
print "Timing factorial of $number\n";
timethese(10000, {
'recursion' => sub { fact1($number) },
'typeglob' => sub { fact2($number) },
'lexical' => sub { fact3($number) },
});
sub validate_factorial_routines {
my $num = shift;
my @result = (fact1($num), fact2($num), fact3($num));
is(fact1(5), 120, 'fact1 should return the correct amount');
is(fact2(5), 120, 'fact2 should return the correct amount');
is(fact3(5), 120, 'fact3 should return the correct amount');
}
sub fact1 {
my ($num) = @_;
return _fact1(1,1,$num);
}
sub _fact1 {
my ($result, $counter, $max) = @_;
return $result if $counter > $max;
return _fact1(($result * $counter), ($counter + 1), $max);
}
sub fact2 {
my ($num) = @_;
@_ = (1, 1, $num);
goto &_fact2;
}
sub _fact2 {
my ($result, $counter, $max) = @_;
return $result if $counter > $max;
@_ = (($result * $counter), ($counter + 1), $max);
goto &_fact2;
}
sub fact3 {
my ($num) = @_;
@_ = (1, 1, $num);
goto $_fact3;
}
__END__
1..3
ok 1 - fact1 should return the correct amount
ok 2 - fact2 should return the correct amount
ok 3 - fact3 should return the correct amount
Testing factorial of 30
120
Benchmark: timing 10000 iterations of lexical, recursion, typeglob...
lexical: 4 wallclock secs ( 4.05 usr + 0.00 sys = 4.05 CPU) @ 2469.14/s (n=10000)
recursion: 1 wallclock secs ( 1.45 usr + 0.00 sys = 1.45 CPU) @ 6896.55/s (n=10000)
typeglob: 5 wallclock secs ( 4.28 usr + 0.00 sys = 4.28 CPU) @ 2336.45/s (n=10000)
####
1..3
ok 1 - fact1 should return the correct amount
ok 2 - fact2 should return the correct amount
ok 3 - fact3 should return the correct amount
Timing factorial of 30
Benchmark: timing 10000 iterations of lexical, recursion, typeglob...
lexical: 4 wallclock secs ( 4.05 usr + 0.00 sys = 4.05 CPU) @ 2469.14/s (n=10000)
recursion: 4 wallclock secs ( 3.87 usr + 0.00 sys = 3.87 CPU) @ 2583.98/s (n=10000)
typeglob: 4 wallclock secs ( 4.28 usr + 0.00 sys = 4.28 CPU) @ 2336.45/s (n=10000)