94 lines
1.7 KiB
Lua
94 lines
1.7 KiB
Lua
-- bench_array.lua — array operation benchmark (Lua)
|
|
|
|
local size = 100000
|
|
local clock = os.clock
|
|
|
|
local function bench_push()
|
|
local a = {}
|
|
for i = 0, size - 1 do
|
|
a[#a + 1] = i
|
|
end
|
|
return #a
|
|
end
|
|
|
|
local function bench_index_write()
|
|
local a = {}
|
|
for i = 1, size do a[i] = 0 end
|
|
for i = 1, size do
|
|
a[i] = i - 1
|
|
end
|
|
return a[size]
|
|
end
|
|
|
|
local function bench_seq_read()
|
|
local a = {}
|
|
for i = 1, size do
|
|
a[i] = i - 1
|
|
end
|
|
local s = 0
|
|
for i = 1, size do
|
|
s = s + a[i]
|
|
end
|
|
return s
|
|
end
|
|
|
|
local function bench_reverse()
|
|
local a = {}
|
|
for i = 1, size do
|
|
a[i] = i - 1
|
|
end
|
|
local lo, hi = 1, size
|
|
while lo < hi do
|
|
a[lo], a[hi] = a[hi], a[lo]
|
|
lo = lo + 1
|
|
hi = hi - 1
|
|
end
|
|
return a[1]
|
|
end
|
|
|
|
local function bench_matrix()
|
|
local n = 300
|
|
local mat = {}
|
|
for i = 1, n do
|
|
mat[i] = {}
|
|
for j = 1, n do
|
|
mat[i][j] = (i - 1) * n + (j - 1)
|
|
end
|
|
end
|
|
local s = 0
|
|
for i = 1, n do
|
|
s = s + mat[i][i]
|
|
end
|
|
return s
|
|
end
|
|
|
|
local function bench_filter_count()
|
|
local a = {}
|
|
for i = 1, size do
|
|
a[i] = i - 1
|
|
end
|
|
local count = 0
|
|
for i = 1, size do
|
|
if a[i] % 2 == 0 then
|
|
count = count + 1
|
|
end
|
|
end
|
|
return count
|
|
end
|
|
|
|
local function run(name, fn)
|
|
local start = clock()
|
|
local result = fn()
|
|
local elapsed = (clock() - start) * 1000
|
|
print(string.format(" %s: %.2f ms (result: %s)", name, elapsed, tostring(result)))
|
|
end
|
|
|
|
print("=== Array Benchmark ===")
|
|
print(string.format(" size: %d", size))
|
|
run("push ", bench_push)
|
|
run("index_write ", bench_index_write)
|
|
run("seq_read_sum ", bench_seq_read)
|
|
run("reverse ", bench_reverse)
|
|
run("matrix_300 ", bench_matrix)
|
|
run("filter_count ", bench_filter_count)
|