lua案例
lua print输出到文件中
- 自定义print函数,使用io.output输出
- 后续可以通过“io.output”灵活切换到其它文件
wsk@wsk:~/test$ lua
Lua 5.2.4 Copyright (C) 1994-2015 Lua.org, PUC-Rio
> print = function(...) io.output():write(...) end
> io.output("lua.txt")
> print("123\n")
> print("hello world\n")
> os.exit()
wsk@wsk:~/test$ cat lua.txt
123
hello world
lua 中的时间戳
socket.gettime()
精确到msos.time()
: 应该是返回当前时间点距离1970-01-01
的秒数 📌 精确到sos.clock()
: CPU时钟 📌 可以精确到0.01sos.date()
: 时间字符串化
关注当前时间
关注时间差
时间精确到0.01秒
wsk@wsk:~/test$ lua
Lua 5.2.4 Copyright (C) 1994-2015 Lua.org, PUC-Rio
> start_t = os.clock()
> end_t = os.clock()
> print(string.format("start time : %.4f", start_t))
start time : 0.0010
> print(string.format("end time : %.4f", end_t))
end time : 0.0011
> print(string.format("use time : %.4f", end_t-start_t))
use time : 0.0001
> os.exit()
时间精确到毫秒
时间, 依赖外部源码包, 可以使用luasocket
编译安装的时候,你可能需要在源码包根目录下的config文件中指定LUAINC变量为你的lua路径
local socket = require "socket"
local t0 = socket.gettime()
-- do something
local t1 = socket.gettime()
print("used time: "..t1-t0.."ms")
lua 延时
- 占用大量CPU资源,不推荐使用
function Sleep(n)
local t0 = os.clock()
while os.clock() - t0 <= n do end
end
- 调用系统函数sleep,不消耗cpu资源,推荐使用
注:如果使用os.clock()来进行计时,不能使用sleep
function Sleep(n)
os.execute("sleep " .. n)
end
参考
本文来自博客园,作者:whilewell,转载请注明原文链接:https://www.cnblogs.com/viiv/p/15794974.html