Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Demonstrate the difference of time cost iterating over ffi array of double versus native array both with luajit
- require "os"
- local ffi = require("ffi")
- local num_ele = 900000
- local num_pass = 50000
- function elap(beg_time, msg)
- local end_time = os.clock()
- print ("elap " .. msg .. " " .. end_time - beg_time .. "sec")
- return os.clock()
- end
- local begt = os.clock()
- local arr = ffi.new("double[?]", num_ele + 1)
- begt = elap(begt, "allocate ffi")
- -- fill the array for the example, here you would fill it from a file
- local begt = os.clock()
- for i = 0, num_ele do
- arr[i] = i
- end
- begt = elap(begt, "fill ffi array")
- local sum_start = ffi.cast("double", 0)
- for pass = 0, num_pass do
- local sum = sum_start
- for i = 0, num_ele do
- sum = sum + arr[i]
- end
- end
- begt = elap(begt, "sum the ffi arrray")
- for pass = 0, num_pass do
- local sum1 = 0
- for i = num_ele,0,-1 do
- sum1 = sum1 + arr[i]
- end
- end
- begt = elap(begt, "sum the ffi arrray in reverse")
- --------------
- --- Test with Native Lua Table
- --------------
- tt = {}
- local begt = os.clock()
- for i = 0, num_ele do
- tt[i] = i
- end
- begt = elap(begt, "fill native table ")
- for pass = 0, num_pass do
- local sum2 = 0
- for i = 0, num_ele do
- sum2 = sum2 + tt[i]
- end
- end
- begt = elap(begt, "sum the lua arrray")
- for pass = 0, num_pass do
- local sum3 = 0
- for i = num_ele,0,-1 do
- sum3 = sum3 + tt[i]
- end
- end
- begt = elap(begt, "sum the lua arrray in reverse")
- assert(sum == sum1, "warning sum1 ~= sum")
- assert(sum == sum2, "warning the two sum2 ~= sum")
- assert(sum == sum3, "warning the two sum3 ~= sum")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement