Advertisement
Guest User

-- Demonstrate the difference of time cost iterating over ff

a guest
Dec 10th, 2014
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- Demonstrate the difference of time cost iterating over ffi array of double versus native array both with 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, num_ele do
  29.         sum = sum + arr[i]
  30.   end
  31. end
  32. begt = elap(begt, "sum the ffi arrray")
  33.      
  34.      
  35. for pass = 0, num_pass do
  36.   local sum1 = 0
  37.   for i =  num_ele,0,-1 do
  38.         sum1 = sum1 + arr[i]
  39.   end
  40. end
  41. begt = elap(begt, "sum the ffi arrray in reverse")
  42.  
  43.      
  44.  --------------
  45.  --- Test with Native Lua Table
  46.  --------------
  47.  tt = {}
  48. local begt = os.clock()
  49. for i = 0, num_ele do
  50.     tt[i] = i
  51. end
  52. begt = elap(begt, "fill native table ")
  53.  
  54.  
  55.  
  56. for pass = 0, num_pass do
  57.   local sum2 = 0
  58.   for i = 0, num_ele do
  59.         sum2 = sum2 + tt[i]
  60.   end
  61. end
  62. begt = elap(begt, "sum the lua arrray")
  63.  
  64.  
  65.  
  66. for pass = 0, num_pass do
  67.   local sum3 = 0
  68.   for i = num_ele,0,-1  do
  69.         sum3 = sum3 + tt[i]
  70.   end
  71. end
  72. begt = elap(begt, "sum the lua arrray in reverse")
  73.  
  74. assert(sum == sum1, "warning sum1 ~= sum")
  75. assert(sum == sum2,  "warning the two sum2 ~= sum")
  76. assert(sum == sum3,  "warning the two sum3 ~= sum")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement