Last active
October 24, 2022 19:32
-
-
Save dpino/647b9d2e12aa8ff859b4 to your computer and use it in GitHub Desktop.
Measures performance of loops iterating with pairs, ipairs and indexing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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
Line 54 should be
x=a[j]
then the results will change to