如何使用时间命令但只对脚本的一部分计时

How to use time command but only to time part of the script

郑重声明,我 运行正在 Unix Solaris 系统中使用 ksh。 我有一个看起来像这样的脚本:

awk '{ do stuff here }'

for n in x {
    echo $something | awk '{ do more stuff here }'
}

我知道我可以在 运行 脚本时在控制台中使用 time,例如,如果文件名是 file_name,我会运行 它是这样的:time ksh file_name,但是像这样我得到了整个脚本的 运行 时间,我只需要 for 的 运行 时间为了与另一个脚本进行比较进行一些计算。我什至可以在脚本中调用 time 吗,所以可以说我会在 for 之前添加它,以便它只计算那部分?另外我想知道一个脚本是否可以有两个 time,这样你就可以得到脚本两个不同部分的 运行 时间。

由于 Bash 脚本中的所有变量都是全局变量,您可以将 for 存储在函数中并在 time:

之前调用它
my_for_function () {
    for n in x {
        echo $something | awk '{ do more stuff here }'
    }
}

awk '{ do stuff here }'

time my_for_function   # here you call `time`

那你运行脚本就正常了。

小例子

$ cat silly_script.sh

myfunc() {
    for x in "${a[@]}"
        do
             echo "$x --"
             sleep 1
        done

}

awk 'BEGIN {print "i am here"}'
a=(1 2 3 4)

time myfunc

echo "i am done"

让我们运行它:

$ bash silly_script.sh
i am here
1 --
2 --
3 --
4 --

real    0m4.008s
user    0m0.004s
sys 0m0.000s
i am done