[root@localhost ~]# time ls anaconda-ks.cfg install.log install.log.syslog satools text
real 0m0.009s
user 0m0.002s
sys 0m0.007s
输出的信息分别显示了该命令所花费的real时间、user时间和sys时间。
real时间是指挂钟时间,也就是命令开始执行到结束的时间。这个短时间包括其他进程所占用的时间片,和进程被阻塞时所花费的时间。
user时间是指进程花费在用户模式中的CPU时间,这是唯一真正用于执行进程所花费的时间,其他进程和花费阻塞状态中的时间没有计算在内。
sys时间是指花费在内核模式中的CPU时间,代表在内核中执系统调用所花费的时间,这也是真正由进程使用的CPU时间
Shell计时
在Linux的Shell下,我们经常也使用Shell内置的time命令和GNU版的time命令来测试程序运行的时间。
内置的time提供的参数选项比较少,而GNU的time则提供了丰富的参数选项,包括指定输出文件等功能。[grandiose@Bygone grandiose]$ /usr/bin/time --output=foo.txt foo
上句只有时间信息输出到了foo.txt文件中,如果想要包括foo执行的结果,就需要按下句这样使用:[grandiose@Bygone grandiose]$ /usr/bin/time --output=foo.txt --append foo >foo.txt
如果想要控制输出时间的格式,可以使用-f开关进行格式化:[grandiose@Bygone grandiose]$ /usr/bin/time
--output=foo.txt -f "\\t%E real,\\t%U user,\\t%S sys" foo
如果仍需要使用Shell内置的time命令,可以用下面一句将结果输出至文件:[grandiose@Bygone grandiose]$ (time foo) 2>foo.txt
这样写是因为内置命令time的输出是到标准错误的,文件描述符2表示标准错误stderr。如果还想要包括foo执行的结果,就要这样:[grandiose@Bygone grandiose]$ (time foo) >foo.txt 2>&1
其中2>&1的含义是2与1 相同,一起送入foo.txt中。
nohup命令可以保证进程在退出系统之后仍能运行,这是它的常规用法。我们也可以这样使用nohup:[grandiose@Bygone grandiose]$ nohup time foo
结果全部输出至nohup.out,也包括程序运行的时间信息。可以使用下面的语句将时间信息输出至文件foo.txt中。[grandiose@Bygone grandiose]$ tail -2 nohup.out > foo.txt
为了保证和POSIX一致,输出的时间格式为(nohup.out中的内容除外):real 0m0.007s
user 0m0.002s
sys 0m0.004s
我们可以使用linux下面一些过滤命令如awk、sed、grep、tr等过滤出我们想要得到的内容,例如想要得到real段对应的时间:[grandiose@Bygone grandiose]$ grep real foo.txt | cut -f2,或者
[grandiose@Bygone grandiose]$ sed -n '2p' foo.txt | cut -f2
在Shell下,输出的时间精度为毫秒级,如果需要微秒级的计时,那就应该在程序中进行处理。