示例工程 31-luajit-and-ffi
31-luajit-and-ffi/03-jit-on-off-bench/main.lua
-- @runtimes luajit
--- 演示:JIT 开/关对密集循环的影响。
local M = {}
local function work(n)
local total = 0
for i = 1, n do
total = total + i
end
return total
end
--- @return table { on_time = number, off_time = number, jit = boolean }
function M.run(log)
log = log or print
local jit = require("jit")
jit.on()
local started = os.clock()
local a = work(200000)
local on_time = os.clock() - started
jit.off(work, true)
started = os.clock()
local b = work(200000)
local off_time = os.clock() - started
jit.on(work, true)
log(("on_positive=%s off_positive=%s"):format(tostring(a > 0), tostring(b > 0)))
return { on_time = on_time, off_time = off_time, jit = true }
end
if not ... then
M.run()
end
return M