Advertisement
Guest User

Untitled

a guest
May 26th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. local ffi = require 'ffi'
  2.  
  3. local intidx_fnc do
  4. if ffi.abi('le') then
  5. function intidx_fnc(n)
  6. if n<1 or n>4 then
  7. error("wrong index", 2)
  8. end
  9. return n-1
  10. end
  11. else
  12. function intidx_fnc(n)
  13. if n<1 or n>4 then
  14. error("wrong index", 2)
  15. end
  16. return 4-n
  17. end
  18. end
  19. end
  20.  
  21. local intidx_tab do
  22. intidx_tab = setmetatable({}, {__index = function(self, index)
  23. local res = intidx_fnc(index)
  24. rawset(self, index, res)
  25. return res
  26. end})
  27. end
  28.  
  29. local function bench(f)
  30. local before = os.clock()
  31. f()
  32. return os.clock() - before
  33. end
  34.  
  35. local function compare(vals)
  36. for key, value in pairs(vals) do
  37. print(key, bench(value))
  38. end
  39. end
  40.  
  41. local num = 1e9
  42. compare {
  43. ['function'] = function()
  44. for i=1,num do
  45. local a = intidx_fnc(i % 3 + 1)
  46. end
  47. end;
  48. ['table'] = function()
  49. for i=1,num do
  50. local a = intidx_tab[i % 3 + 1]
  51. end
  52. end;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement