Created
January 20, 2011 06:19
-
-
Save brixen/787496 to your computer and use it in GitHub Desktop.
This file contains 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
require "benchmark" | |
N = (ARGV.shift || 40).to_i | |
def fib(n) | |
return n if n < 2 | |
fib(n-2) + fib(n-1) | |
end | |
Benchmark.bmbm do |x| | |
x.report("fib(#{N})") { fib N } | |
end |
This file contains 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
function fib(n) | |
if n < 2 then return 1 | |
else return fib(n-2) + fib(n-1) end | |
end | |
print(fib(40)) |
This file contains 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
gauss:rubinius brian$ time lua -v fib.lua | |
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio | |
165580141 | |
real 0m49.459s | |
user 0m46.261s | |
sys 0m0.217s | |
LuaJIT 2.0.0-beta5 -- Copyright (C) 2005-2010 Mike Pall. http://luajit.org/ | |
165580141 | |
real 0m12.862s | |
user 0m12.090s | |
sys 0m0.054s | |
gauss:rubinius brian$ rbx -v work/bench/bm_fib.rb | |
rubinius 1.2.1dev (1.8.7 aa7535ab 2010-12-21 JI) [i686-apple-darwin9.8.0] | |
Rehearsal ------------------------------------------- | |
fib(40) 9.221481 0.035743 9.257224 ( 9.767241) | |
---------------------------------- total: 9.257224sec | |
user system total real | |
fib(40) 9.203364 0.038571 9.241935 ( 9.770584) | |
gauss:rubinius brian$ rbx -v -Xint work/bench/bm_fib.rb | |
rubinius 1.2.1dev (1.8.7 aa7535ab 2010-12-21) [i686-apple-darwin9.8.0] | |
Rehearsal ------------------------------------------- | |
fib(40) 29.933660 0.140400 30.074060 ( 32.344898) | |
--------------------------------- total: 30.074060sec | |
user system total real | |
fib(40) 29.278165 0.127529 29.405694 ( 31.091665) |
Yep
Reverse the recursion and the LuaJIT version becomes many times faster (fib(n-1) + fib(n-2)). Down-recursive trace can be unrolled then, Mike said.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Isn't rather unfair to benchmark lua with
time
while benchmarking rbx in process?