-
-
Save nothingmuch/223431 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!perl -w | |
use strict; | |
use Benchmark qw(:all); | |
use Sub::Call::Tail; | |
no warnings 'recursion'; | |
sub rec_sum { | |
if ( $_[0] == 0 ) { | |
return 0; | |
} else { | |
return 1 + rec_sum($_[0]-1); | |
} | |
} | |
sub sum { | |
if ( $_[0] == 0 ) { | |
return $_[1]; | |
} else { | |
sum( $_[0] - 1, $_[1] + 1 ); | |
} | |
} | |
sub tail_sum { | |
if ( $_[0] == 0 ) { | |
return $_[1]; | |
} else { | |
tail tail_sum( $_[0] - 1, $_[1] + 1 ); | |
} | |
} | |
sub goto_sum { | |
if ( $_[0] == 0 ) { | |
return $_[1]; | |
} else { | |
@_ = ( $_[0] - 1, $_[1] + 1 ); | |
goto &goto_sum; | |
} | |
} | |
foreach my $n ( map { 10 ** $_ } 0 .. 6 ) { | |
print "testing sum($n)...\n"; | |
cmpthese -5 => { | |
tail => sub{ | |
tail_sum($n, 0); | |
}, | |
goto => sub{ | |
goto_sum($n, 0); | |
}, | |
rec_accum => sub{ | |
sum($n, 0); | |
}, | |
rec => sub { | |
rec_sum($n); | |
}, | |
}; | |
print "\n"; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
testing sum(1)... | |
Rate goto tail rec_accum rec | |
goto 472421/s -- -45% -47% -50% | |
tail 854544/s 81% -- -5% -10% | |
rec_accum 896098/s 90% 5% -- -6% | |
rec 953999/s 102% 12% 6% -- | |
testing sum(10)... | |
Rate goto tail rec rec_accum | |
goto 74387/s -- -48% -50% -51% | |
tail 141738/s 91% -- -4% -6% | |
rec 147540/s 98% 4% -- -2% | |
rec_accum 150404/s 102% 6% 2% -- | |
testing sum(100)... | |
Rate goto tail rec rec_accum | |
goto 7933/s -- -48% -49% -51% | |
tail 15228/s 92% -- -2% -5% | |
rec 15552/s 96% 2% -- -3% | |
rec_accum 16105/s 103% 6% 4% -- | |
testing sum(1000)... | |
Rate goto tail rec rec_accum | |
goto 793/s -- -49% -49% -52% | |
tail 1555/s 96% -- -0% -5% | |
rec 1559/s 97% 0% -- -5% | |
rec_accum 1634/s 106% 5% 5% -- | |
testing sum(10000)... | |
Rate goto rec rec_accum tail | |
goto 78.3/s -- -41% -44% -49% | |
rec 132/s 68% -- -5% -14% | |
rec_accum 140/s 78% 6% -- -9% | |
tail 153/s 95% 16% 9% -- | |
testing sum(100000)... | |
Rate goto rec rec_accum tail | |
goto 7.71/s -- -39% -44% -50% | |
rec 12.7/s 64% -- -8% -17% | |
rec_accum 13.7/s 78% 8% -- -10% | |
tail 15.3/s 98% 20% 11% -- | |
testing sum(1000000)... | |
Rate goto rec rec_accum tail | |
goto 0.783/s -- -36% -42% -48% | |
rec 1.22/s 55% -- -10% -19% | |
rec_accum 1.35/s 72% 11% -- -10% | |
tail 1.50/s 92% 24% 12% -- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment