关于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'

其他回答

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

time -o outfile command

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

#!/bin/bash

set -e

_onexit() {
    [[ $TMPD ]] && rm -rf "$TMPD"
}

TMPD="$(mktemp -d)"
trap _onexit EXIT

_time_2() {
    "$@" 2>&3
}

_time_1() {
    time _time_2 "$@"
}

_time() {
    declare time_label="$1"
    shift
    exec 3>&2
    _time_1 "$@" 2>"$TMPD/timing.$time_label"
    echo "time[$time_label]"
    cat "$TMPD/timing.$time_label"
}

_time a _do_something
_time b _do_another_thing
_time c _finish_up

这样做的好处是不生成子壳,并且最终的管道有它的stderr恢复为真正的stderr。

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

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

例如:

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

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

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

$ (time ls) > outfile 2>&1

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

$ (time ls) > ls_results 2> time_results

我最终使用:

/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不一样