Advertisement
Guest User

Demonstrate the difference of time cost ieterating over ffi

a guest
Dec 10th, 2014
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.14 KB | None | 0 0
  1. -- Demonstrate the difference of time cost ieterating over ffi array of double versus native table both using luajit
  2.  
  3. require "os"
  4. local ffi = require("ffi")  
  5. local num_ele = 900000
  6. local num_pass = 50000
  7. function elap(beg_time, msg)
  8.   local end_time = os.clock()
  9.   print ("elap " .. msg ..  " " .. end_time - beg_time .. "sec")
  10.   return os.clock()
  11. end
  12.  
  13. local begt = os.clock()
  14. local arr = ffi.new("double[?]", num_ele + 1)
  15. begt = elap(begt, "allocate ffi")
  16.  
  17.      
  18. -- fill the array for the example, here you would fill it from a file
  19. local begt = os.clock()
  20. for i = 0, num_ele do
  21.     arr[i] = i
  22. end
  23.  
  24. begt = elap(begt, "fill ffi array")
  25.  
  26. for pass = 0, num_pass do
  27.   local sum = 0
  28.   for i = 0, 9999 do
  29.         sum = sum + arr[i]
  30.   end
  31. end
  32. begt = elap(begt, "sum the ffi arrray")
  33.      
  34.  
  35.  --------------
  36.  --- Test with Native Lua Table
  37.  --------------
  38.  tt = {}
  39. local begt = os.clock()
  40. for i = 0, num_ele do
  41.     tt[i] = i
  42. end
  43. begt = elap(begt, "fill native table ")
  44.  
  45.  
  46. local sum2 = 0
  47. for pass = 0, num_pass do
  48.   for i = 0, num_ele do
  49.         sum2 = sum2 + tt[i]
  50.   end
  51. end
  52. begt = elap(begt, "sum the lua arrray")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement