Skip to content

Instantly share code, notes, and snippets.

@brixen
Created January 20, 2011 06:19
Show Gist options
  • Save brixen/787496 to your computer and use it in GitHub Desktop.
Save brixen/787496 to your computer and use it in GitHub Desktop.
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
function fib(n)
if n < 2 then return 1
else return fib(n-2) + fib(n-1) end
end
print(fib(40))
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)
@MikePall
Copy link

Please learn about some Lua basics before attempting to benchmark it. Use "local function fib(n)" and it runs 30% faster with LuaJIT.
Oh, and performance on this benchmark is completely irrelevant unless your application is computing Fibonacci numbers all day long.

@brixen
Copy link
Author

brixen commented Jan 20, 2011

Interesting. But like you say, this is completely irrelevant. ;)

@rkh
Copy link

rkh commented Jan 20, 2011

Isn't rather unfair to benchmark lua with time while benchmarking rbx in process?

@brixen
Copy link
Author

brixen commented Jan 20, 2011

Yep

@olov
Copy link

olov commented Apr 26, 2011

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