View difference between Paste ID: EghuB2BV and jniGqHyp
SHOW: | | - or go back to the newest paste.
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
local sum_start = ffi.cast("double", 0)
27-
  local sum = 0
27+
28
  local sum = sum_start
29
  for i = 0, num_ele do
30
        sum = sum + arr[i]
31
  end
32
end
33
begt = elap(begt, "sum the ffi arrray")
34
     
35
     
36
for pass = 0, num_pass do
37
  local sum1 = 0
38
  for i =  num_ele,0,-1 do
39
        sum1 = sum1 + arr[i]
40
  end
41
end
42
begt = elap(begt, "sum the ffi arrray in reverse")
43
44
     
45
 --------------
46
 --- Test with Native Lua Table
47
 --------------
48
 tt = {}
49
local begt = os.clock()
50
for i = 0, num_ele do
51
    tt[i] = i
52
end
53
begt = elap(begt, "fill native table ")
54
55
56
57
for pass = 0, num_pass do
58
  local sum2 = 0
59
  for i = 0, num_ele do
60
        sum2 = sum2 + tt[i]
61
  end
62
end
63
begt = elap(begt, "sum the lua arrray")
64
65
66
67
for pass = 0, num_pass do
68
  local sum3 = 0
69
  for i = num_ele,0,-1  do
70
        sum3 = sum3 + tt[i]
71
  end
72
end
73
begt = elap(begt, "sum the lua arrray in reverse")
74
75
assert(sum == sum1, "warning sum1 ~= sum")
76
assert(sum == sum2,  "warning the two sum2 ~= sum")
77
assert(sum == sum3,  "warning the two sum3 ~= sum")