Skip to content

Instantly share code, notes, and snippets.

@dpino

dpino/perf-iterators.lua

Last active Aug 29, 2015
Embed
What would you like to do?
Measures performance of loops iterating with pairs, ipairs and indexing
#!/usr/bin/env luajit
--[[
Environment: Lenovo ThinkPad X200 / 16GB RAM / iCore7 2620M (2.70GHz, 4MB Cache)
| pairs | ipairs | indexing |
| 1.000000 | 5.244480 | 9.388388 |
| 0.190677 | 1.000000 | 1.790146 |
| 0.106515 | 0.558614 | 1.000000 |
]]--
local function array(n)
local result = {}
for i=1, n do
table.insert(result, tostring(i))
end
return result
end
local function execute_times(f, times)
local a = array(100)
local begin = os.clock()
for i=1,times do
f(a)
end
local finish = os.clock()
return finish - begin
end
local times = {}
local ITERATIONS = 1000000
-- Pairs
local elapse_time = execute_times(function(a)
for j,v in pairs(a) do
x=v
end
end, ITERATIONS)
times["pairs"] = elapse_time
-- iPairs
local elapse_time = execute_times(function(a)
for _,v in ipairs(a) do
x=v
end
end, ITERATIONS)
times["ipairs"] = elapse_time
-- Indexing
local elapse_time = execute_times(function(a)
for j=1,#a do
x=v
end
end, ITERATIONS)
times["indexing"] = elapse_time
local results = {
{ times["pairs"]/times["pairs"], times["pairs"]/times["ipairs"], times["pairs"]/times["indexing"] },
{ times["ipairs"]/times["pairs"], times["ipairs"]/times["ipairs"], times["ipairs"]/times["indexing"] },
{ times["indexing"]/times["pairs"], times["indexing"]/times["ipairs"], times["indexing"]/times["indexing"] },
}
print("| pairs | ipairs | indexing |")
for _, row in ipairs(results) do
io.write(string.format("| %.6f ", row[1]))
io.write(string.format("| %.6f |", row[2]))
io.write(string.format(" %.6f |", row[3]))
io.write("\n")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.