在Lua中计时一个函数/任务。

我正在尝试确定我的Lua代码中某些语句的运行时间。

我的代码看起来像这样:

function test(self)
    local timer1
    local timer2
    local timer3
    timer1 = os.time()
    print('timer1 start time is:'.. timer1)
    --do some stuff.
    print( 'Timer1 end time is:' , os.difftime(os.time(), timer1) )
    timer2 = os.time()
    print('timer2 start time is:'.. timer2)

    -- do a lot of stuff
    print( 'Timer2 end time is:' , os.difftime(os.time(), timer2) )

    timer3=os.time()
    print('timer3 start time is:'.. timer3)

    -- a lot of processing...

    print( 'Timer3 end time is:' , os.difftime(os.time(), timer3) )
end

输出如下:

timer1 start time is:1401798084
Timer1 end time is: = 0
timer2 start time is:1401798084
Timer2 end time is: = 0
timer3 start time is:1401798084
Timer3 end time is: = 2

我尝试过的其他方法:

Lua - Current time in milliseconds

在上述帖子中,我找到了这段代码:

local x = os.clock()
local s = 0
for i=1,100000 do s = s + i end
os.execute("sleep "..1)
print(string.format("elapsed time: %.2f\n", os.clock() - x))

我添加了睡眠时间...但当它运行时,我得到的输出是:

elapsed time: 0.00

显然我做错了什么。如果您对我如何修复/改进这个方法有建议,我全听着。在此期间,我将重新访问lua网站以了解os.difftime()是否使用不正确。

编辑1

我将测试代码更改为:

local x = os.clock()
local s = 0
for i=1,100000 do
    s = s + i
    os.execute("sleep "..1)
end
print(string.format("elapsed time: %.2f\n", os.clock() - x))

现在我得到了一些有意义的值!

原文链接 https://stackoverflow.com/questions/24015241

点赞
stackoverflow用户258523
stackoverflow用户258523

这段代码进行了很多次加法运算,然后执行一次为一秒的 sleep 调用。

for i=1,100000 do s = s + i end
os.execute("sleep "..1)

这段代码进行了相同次数的加法运算,但每次通过循环时都睡眠了一秒。

for i=1,100000 do
   s = s + i
   os.execute("sleep "..1)
end

这是一个很大的区别。

2014-06-03 13:16:58
stackoverflow用户107090
stackoverflow用户107090

os.clock 用于测量 CPU 时间,而不是墙钟时间。CPU 时间不包括 sleep 中花费的时间,所以下面的脚本仍然会打印出零的经过时间:

local x = os.clock()
os.execute("sleep 60")
print(string.format("elapsed time: %.2f\n", os.clock() - x))

当你将 os.execute 移到循环中时,你测量的可能是分叉 shell 的时间。下面的脚本即使是一个短循环,它也会打印出非零的经过时间:

local x = os.clock()
for i=1,1000 do os.execute("true") end
print(string.format("elapsed time: %.2f\n", os.clock() - x))

最后,第一个循环中得到的零经过时间是因为 Lua 很快。尝试将限制更改为 1000000:

local x = os.clock()
local s = 0
for i=1,1000000 do s = s + i end
print(string.format("elapsed time: %.2f\n", os.clock() - x))
2014-06-03 14:05:27