Skip to content

Instantly share code, notes, and snippets.

@peczenyj
Created June 5, 2011 18:40
Show Gist options
  • Save peczenyj/1009259 to your computer and use it in GitHub Desktop.
Save peczenyj/1009259 to your computer and use it in GitHub Desktop.
fibonacci examples
use Modern::Perl;
use Attribute::Memoize;
use Inline qw(C);
=cut
Benchmark: running memoize, nativo, nativo_memoize, normal for at least 2 CPU seconds...
   memoize: 2.086 wallclock secs ( 2.08 usr +  0.01 sys =  2.09 CPU) @ 299315.79/s (n=625570)
    nativo: 2.2446 wallclock secs ( 2.24 usr +  0.01 sys =  2.25 CPU) @ 3131.11/s (n=7045)
nativo_memoize: 2.04854 wallclock secs ( 2.05 usr +  0.00 sys =  2.05 CPU) @ 291284.88/s (n=597134)
    normal: 2.07676 wallclock secs ( 2.06 usr +  0.00 sys =  2.06 CPU) @ 13.59/s (n=28)
                   Rate        normal        nativo nativo_memoize       memoize
normal           13.6/s            --         -100%          -100%         -100%
nativo           3131/s        22936%            --           -99%          -99%
nativo_memoize 291285/s      2142924%         9203%             --           -3%
memoize        299316/s      2202009%         9459%             3%            --
=cut
sub fib {
my $i = shift;
return ($i == 1 || $i == 2) ? 1 : fib($i-1) + fib($i-2);
}
sub fibm : Memoize {
my $i = shift;
return ($i == 1 || $i == 2) ? 1 : fib($i-1) + fib($i-2);
}
sub fibC($);
use Memoize;
memoize('fibD');
sub fibD($); # :Memoize nao funcionou;
use Benchmark qw( timethese cmpthese :hireswallclock) ;
my $x = 25;
my $r = timethese( -2, {
normal => sub { fib $x } ,
memoize => sub { fibm $x } ,
nativo => sub { fibC $x } ,
nativo_memoize => sub { fibD $x } ,
} );
cmpthese $r;
__END__
__C__
int fibC(int i){
return (i == 1 || i == 2) ? 1 : fibC(i-1) + fibC(i-2);
}
int fibD(int i){
return (i == 1 || i == 2) ? 1 : fibD(i-1) + fibD(i-2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment