Skip to content

Instantly share code, notes, and snippets.

@Choumiko
Created October 19, 2016 08:02
Show Gist options
  • Save Choumiko/7169004f0ae31eb530f66150294b05c9 to your computer and use it in GitHub Desktop.
Save Choumiko/7169004f0ae31eb530f66150294b05c9 to your computer and use it in GitHub Desktop.
Script to test performance of functions
Position = {}
function Position.to_table(pos_arr)
--fail_if_missing(pos_arr, "missing position argument")
if #pos_arr == 2 then
return { x = pos_arr[1], y = pos_arr[2] }
end
return pos_arr
end
function Position.distance_squared(pos1, pos2)
pos1 = Position.to_table(pos1)
pos2 = Position.to_table(pos2)
local axbx = pos1.x - pos2.x
local ayby = pos1.y - pos2.y
return axbx * axbx + ayby * ayby
end
--local abs = math.abs
function Position.manhattan_distance(pos1, pos2)
pos1 = Position.to_table(pos1)
pos2 = Position.to_table(pos2)
return math.abs(pos2.x - pos1.x) + math.abs(pos2.y - pos1.y)
end
local function printf(...)
io.write(string.format(...))
end
local socket = require 'socket'
local tbl = {}
for j=1,160 do
tbl[j] = {x=j,y=j+2}
end
local testPos = {x = 9001, y = -1337}
for loops=0,10000,100 do
--for loops=0,100000,1000 do
printf("%6d loops ",loops)
local t0=socket.gettime()
for i=1,loops do
for _, pos in pairs(tbl) do
Position.distance_squared(testPos, pos)
end
end
local t1=socket.gettime()
local m = (t1-t0)
--if t1>t0 then break end
t0=socket.gettime()
for i=1,loops do
for _, pos in pairs(tbl) do
Position.manhattan_distance(testPos, pos)
end
end
t1=socket.gettime()
local a = (t1-t0)
printf(" c=%9.6f ms", (m-a)*1000)
printf(" squared=%9.3f ms ",m*1000)
printf(" manhattan=%9.3f ms\n",a*1000)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment