示例工程 03-numbers

03-numbers/05-number-bench/main.lua

lua · 0.9 KB

-- @runtimes lua54 luajit
--- 演示:整数加法与浮点加法的相对成本,并暴露 LuaJIT 没有整数子类型。
 
local M = {}
 
local N = 1000000
 
--- @return table { int_time = number, float_time = number, has_integer = boolean }
function M.run(log)
	log = log or print
	local has_integer = math.type ~= nil and math.type(1) == "integer"
 
	local sum = 0
	local started = os.clock()
	for i = 1, N do
		sum = sum + i
	end
	local int_time = os.clock() - started
 
	local total = 0.0
	started = os.clock()
	for i = 1, N do
		total = total + i / 1
	end
	local float_time = os.clock() - started
 
	log(("has_integer_subtype=%s"):format(tostring(has_integer)))
	log(("int_positive=%s"):format(tostring(sum > 0)))
	log(("float_positive=%s"):format(tostring(total > 0)))
	return { int_time = int_time, float_time = float_time, has_integer = has_integer }
end
 
if not ... then
	M.run()
end
 
return M