Advertisement
fuxoft

Lua function performance comparison

Feb 11th, 2013
565
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.54 KB | None | 0 0
  1. #!/usr/bin/env lua
  2. # Lua speed comparison
  3.  
  4. local function measure (fn)
  5.     local t0 = os.clock()
  6.     for i = 1,10000 do
  7.         fn()
  8.     end
  9.     print (os.clock() - t0 .. " seconds")
  10. end
  11.  
  12. local function v1()
  13.     local function addv1(n)
  14.         local sum = 0
  15.         for i=1,n do
  16.             if i % 2 == 0 then
  17.                 sum = sum + i
  18.             end
  19.         end
  20.         return sum
  21.     end
  22.     addv1(10000)
  23. end
  24.  
  25. local function addv2(n)
  26.     local sum = 0
  27.     for i=1,n do
  28.         if i % 2 == 0 then
  29.             sum = sum + i
  30.         end
  31.     end
  32.     return sum
  33. end
  34.  
  35. local function v2()
  36.     addv2(10000)
  37. end
  38.  
  39. measure(v1)
  40. measure(v2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement