解决方案
1.在一个死循环中设置一个跳出条件,但是这样的做法会占用大量CPU资源
代码:
cpu消耗结果:
2.调用系统命令
3.借助posix库
代码:
4.借助socket的select
代码:
同样超级的简单,具体的cpu消耗就不贴了,方法很多。
1.在一个死循环中设置一个跳出条件,但是这样的做法会占用大量CPU资源
代码:
[xluren@test time_sleep]$ cat demo.lua
local old_time=os.time()
function demo()
new_time=os.time()
while true
do
if new_time - old_time >100
then
break
end
end
end
demo()
[xluren@test time_sleep]$
cpu消耗结果:
[xluren@test ~]$ pidstat -p 30993 1 60
Linux 2.6.32-220.el6.x86_64 (test.145) 12/07/2014 _x86_64_ (1 CPU)
03:17:37 PM PID %usr %system %guest %CPU CPU Command
03:17:38 PM 30993 97.00 1.00 0.00 98.00 0 lua
03:17:39 PM 30993 97.98 0.00 0.00 97.98 0 lua
03:17:40 PM 30993 98.02 0.00 0.00 98.02 0 lua
03:17:41 PM 30993 99.00 1.00 0.00 100.00 0 lua
03:17:42 PM 30993 97.00 1.00 0.00 98.00 0 lua
^C
[xluren@test ~]$ ps axf |grep 30993
30993 pts/0 R+ 0:38 | \_ lua demo.lua
31039 pts/2 S+ 0:00 \_ grep 30993
[xluren@test ~]$
如此的耗费cpu,所以这种方式 我们直接pass了2.调用系统命令
代码:
[xluren@test time_sleep]$ vim demo_os_cmd.lua
[xluren@test time_sleep]$ lua !$
lua demo_os_cmd.lua
^C[xluren@test time_sleep]$ cat demo_os_cmd.lua
function demo()
os.execute("sleep 100")
end
demo()
[xluren@test time_sleep]$
cpu消耗结果:[xluren@test ~]$ ps axf |grep demo_os_cmd.lua
31144 pts/0 S+ 0:00 | \_ lua demo_os_cmd.lua
31158 pts/2 S+ 0:00 \_ grep demo_os_cmd.lua
[xluren@test ~]$ pidstat -p 31144 1 60
Linux 2.6.32-220.el6.x86_64 (test.145) 12/07/2014 _x86_64_ (1 CPU)
03:20:54 PM PID %usr %system %guest %CPU CPU Command
03:20:55 PM 31144 0.00 0.00 0.00 0.00 0 lua
03:20:56 PM 31144 0.00 0.00 0.00 0.00 0 lua
03:20:57 PM 31144 0.00 0.00 0.00 0.00 0 lua
03:20:58 PM 31144 0.00 0.00 0.00 0.00 0 lua
03:20:59 PM 31144 0.00 0.00 0.00 0.00 0 lua
03:21:00 PM 31144 0.00 0.00 0.00 0.00 0 lua
^C
[xluren@test ~]$
简单,方便,几乎不耗费cpu,可以考虑3.借助posix库
代码:
[xluren@test time_sleep]$ cat demo_posix.lua
require("posix")
function demo()
posix.sleep(100)
end
demo()
[xluren@test time_sleep]$
cpu消耗结果:[xluren@test ~]$ ps axf |grep demo_posix
31327 pts/0 S+ 0:00 | \_ lua demo_posix.lua
31352 pts/2 S+ 0:00 \_ grep demo_posix
[xluren@test ~]$ pidstat -p 31327 1 60
Linux 2.6.32-220.el6.x86_64 (test.145) 12/07/2014 _x86_64_ (1 CPU)
03:25:06 PM PID %usr %system %guest %CPU CPU Command
03:25:07 PM 31327 0.00 0.00 0.00 0.00 0 lua
03:25:08 PM 31327 0.00 0.00 0.00 0.00 0 lua
03:25:09 PM 31327 0.00 0.00 0.00 0.00 0 lua
03:25:10 PM 31327 0.00 0.00 0.00 0.00 0 lua
^C
[xluren@test ~]$
也非常的不错,但是需要安装lua-posix软件包。4.借助socket的select
代码:
[xluren@test time_sleep]$ cat demo_socket.lua
require("socket")
function demo()
socket.select(nil,nil,100)
end
demo()
[xluren@test time_sleep]$
同样超级的简单,具体的cpu消耗就不贴了,方法很多。