在Lua中计时一个函数/任务。
2017-5-23 10:29:22
收藏:0
阅读:134
评论:2
我正在尝试确定我的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用户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
评论区的留言会收到邮件通知哦~
推荐文章
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
- 如何编写 Lua 模式将字符串(嵌套数组)转换为真正的数组?
这段代码进行了很多次加法运算,然后执行一次为一秒的 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
这是一个很大的区别。