fib.lua 605 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. -- fibonacci function with cache
  2. -- very inefficient fibonacci function
  3. function fib(n)
  4. N=N+1
  5. if n<2 then
  6. return n
  7. else
  8. return fib(n-1)+fib(n-2)
  9. end
  10. end
  11. -- a general-purpose value cache
  12. function cache(f)
  13. local c={}
  14. return function (x)
  15. local y=c[x]
  16. if not y then
  17. y=f(x)
  18. c[x]=y
  19. end
  20. return y
  21. end
  22. end
  23. -- run and time it
  24. function test(s,f)
  25. N=0
  26. local c=os.clock()
  27. local v=f(n)
  28. local t=os.clock()-c
  29. print(s,n,v,t,N)
  30. end
  31. n=arg[1] or 24 -- for other values, do lua fib.lua XX
  32. n=tonumber(n)
  33. print("","n","value","time","evals")
  34. test("plain",fib)
  35. fib=cache(fib)
  36. test("cached",fib)