Skip to content

Instantly share code, notes, and snippets.

@pfirsich
Created August 25, 2018 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfirsich/9b870faa6956fc7fefdb2a4c09f74fcf to your computer and use it in GitHub Desktop.
Save pfirsich/9b870faa6956fc7fefdb2a4c09f74fcf to your computer and use it in GitHub Desktop.
Power of Two function benchmark for luajit (löve used for timing)
local potLut = {}
potLut[0] = 1
for i = 1, 32 do
potLut[i] = potLut[i-1] * 2
end
-- compare this with lshift(2, n)
local function potA(n) -- power of two
return potLut[n]
end
local bit = require("bit")
local lshift = bit.lshift
local function potB(n)
return math.abs(lshift(1, n)) -- because lshift(1, 31) = -2147483648
end
local function potBf(n)
return lshift(1, n)
end
local function potC(n)
return 2^n
end
-------------------------------------
local values = {}
for i = 1, 40000000 do
local n = love.math.random(0, 31)
assert(potA(n) == potB(n) and potA(n) == potC(n)) -- potBf is wrong anyways
values[#values + 1] = n
end
local start = love.timer.getTime()
for i = 1, #values do
local res = potA(values[i])
end
print("LUT func: " .. (love.timer.getTime() - start))
local start = love.timer.getTime()
for i = 1, #values do
local res = potLut[values[i]]
end
print("LUT lookup: " .. (love.timer.getTime() - start))
local start = love.timer.getTime()
for i = 1, #values do
local res = potB(values[i])
end
print("bit.lshift: " .. (love.timer.getTime() - start))
local start = love.timer.getTime()
for i = 1, #values do
local res = potBf(values[i])
end
print("bit.lshift without abs: " .. (love.timer.getTime() - start))
local start = love.timer.getTime()
for i = 1, #values do
local res = potC(values[i])
end
print("pow: " .. (love.timer.getTime() - start))
LUT func: 0.066940495627932
LUT lookup: 0.067318620625883
bit.lshift: 0.027310643810779
bit.lshift without abs: 0.029313809820451 (I don't know why it's slower, but this behaviour persists between runs)
pow: 0.059891540324315
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment