Skip to content

Instantly share code, notes, and snippets.

@IgorTimofeev
Last active September 30, 2021 14:21
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 IgorTimofeev/4beb1660a296c69aeb236ce7db15dc2d to your computer and use it in GitHub Desktop.
Save IgorTimofeev/4beb1660a296c69aeb236ce7db15dc2d to your computer and use it in GitHub Desktop.
local uptime = os.clock
local n = 1000000
--------------
local function round1(num)
return num + (2 ^ 52 + 2 ^ 51) - (2 ^ 52 + 2 ^ 51)
end
start = uptime()
for i = 1, n do
round1(1.234)
end
print("Constant ", uptime() - start)
--------------
local huge = 2 ^ 52 + 2 ^ 51
local function round2(num)
return num + huge - huge
end
start = uptime()
for i = 1, n do
round2(1.234)
end
print("Upvalue ", uptime() - start)
--------------
start = uptime()
for i = 1, n do
math.floor(1.234 + 0.5)
end
print("math.floor", uptime() - start)
--------------
local floor = math.floor
start = uptime()
for i = 1, n do
floor(1.234 + 0.5)
end
print("floor (no indexing)", uptime() - start)
--------------
local function round3(num)
return (num + 0.5) // 1
end
start = uptime()
for i = 1, n do
round3(1.234)
end
print("Lua 5.3+: (num + 0.5) // 1 ", uptime() - start)
--------------
local function round4(num)
num = num + 0.5
return num - num % 1
end
start = uptime()
for i = 1, n do
round4(1.234)
end
print("Lua 5.2+: num - num % 1 ", uptime() - start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment