关于Linux上的计时程序有一个小问题:time命令允许 衡量一个程序的执行时间:

[ed@lbox200 ~]$ time sleep 1

real    0m1.004s
user    0m0.000s
sys     0m0.004s

这很好。但是如果我试图将输出重定向到一个文件,它会失败。

[ed@lbox200 ~]$ time sleep 1 > time.txt

real    0m1.004s
user    0m0.001s
sys     0m0.004s

[ed@lbox200 ~]$ cat time.txt 
[ed@lbox200 ~]$ 

我知道还有其他时间的实现有-o选项来写文件,但是 我的问题是关于没有这些选项的命令。

有什么建议吗?


当前回答

如果您使用的是GNU时间而不是bash内置时间,请尝试一下

time -o outfile command

(注意:GNU时间格式与bash内置时间格式略有不同)。

其他回答

如果你正在使用csh,你可以使用:

/usr/bin/time --output=outfile -p $SHELL  -c 'your command'

例如:

/usr/bin/time --output=outtime.txt -p csh -c 'cat file'

如果您使用的是GNU时间而不是bash内置时间,请尝试一下

time -o outfile command

(注意:GNU时间格式与bash内置时间格式略有不同)。

如果你不想触及原始进程的stdout和stderr,你可以将stderr重定向到文件描述符3和返回:

$ { time { perl -le "print 'foo'; warn 'bar';" 2>&3; }; } 3>&2 2> time.out
foo
bar at -e line 1.
$ cat time.out

real    0m0.009s
user    0m0.004s
sys     0m0.000s

你可以使用它作为包装器(例如cronjobs)来监视运行时:

#!/bin/bash

echo "[$(date)]" "$@" >> /my/runtime.log

{ time { "$@" 2>&3; }; } 3>&2 2>> /my/runtime.log
&>out time command >/dev/null

在你的情况下

&>out time sleep 1 >/dev/null

then

cat out

将时间和要计时的命令用括号括起来。

例如,执行下面的ls,并将ls的结果和计时结果写入outfile:

$ (time ls) > outfile 2>&1

或者,如果您想将命令的输出与时间捕获的输出分开:

$ (time ls) > ls_results 2> time_results