关于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选项来写文件,但是 我的问题是关于没有这些选项的命令。

有什么建议吗?


当前回答

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

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

例如:

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

其他回答

&>out time command >/dev/null

在你的情况下

&>out time sleep 1 >/dev/null

then

cat out

由于'time'命令的输出是错误输出,将其重定向为标准输出将更直观地进行进一步处理。

{ time sleep 1; } 2>&1 |  cat > time.txt

如果你只需要shell变量中的时间,那么这是可行的:

var=`{ time <command> ; } 2>&1 1>/dev/null`

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

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

例如:

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

我最终使用:

/usr/bin/time -ao output_file.txt -f "Operation took: %E" echo lol

“a”在哪里附加 “o”前面是要附加到的文件名 哪里的“f”是格式与printf类似的语法 其中“%E”产生0:00:00;小时:分钟:秒 我不得不调用/usr/bin/time,因为bash“time”正在践踏它,并且没有相同的选项 我只是想输出到文件,和OP不一样