示例工程 26-testing-and-lint
26-testing-and-lint/03-loose-perf-assert/main.lua
-- @runtimes lua54 luajit
--- 演示:性能断言只比较量级。
local M = {}
local function sum_loop(n)
local total = 0
for i = 1, n do
total = total + i
end
return total
end
--- @return table { fast = number, slow = number, ratio_ok = boolean }
function M.run(log)
log = log or print
local function time(fn, n)
local started = os.clock()
fn(n)
return os.clock() - started
end
local fast = time(sum_loop, 1000)
local slow = time(sum_loop, 100000)
local ratio_ok = slow > fast
log(("ratio_ok=%s"):format(tostring(ratio_ok)))
return { fast = fast, slow = slow, ratio_ok = ratio_ok }
end
if not ... then
M.run()
end
return M