如何将时间函数的输出重定向到变量
How to redirect the output of time function to a variable
我有以下问题需要您的帮助来解决。
我有一个函数可以称之为 "fun"
,我想计算函数需要多少时间 运行,所以我在脚本中添加了这一行:
time fun;
所以像这样,它还会打印函数 运行 所需的时间。重点是我想将 time
的输出重定向到一个变量中,这样我可以稍后根据需要对其进行操作。我已经尝试失败了:
TIME=`time fun`
time fun | tail -3
etc..
有谁知道如何做到这一点,例如,期望的结果是:
somehow add the time output in TIME variable.
所以如果我愿意 echo $TIME
我会得到这样的结果,
real 0m0.45s
user 0m0.35s
sys 0m0.00s
感谢您的宝贵时间!
P.S.
我 运行 Oracle solaris 系统上的 ksh 脚本。
您可以使用 How can I redirect the output of 'time' to a variable or file? 描述的内容:
your_time=$( { time fun ; } 2>&1 >/dev/null)
在这里,我们将 stdout 重定向到 /dev/null
,这样我们就可以摆脱它,只获取 stderr。这是一个特例:
foo=$( { time ls; } 2>&1 ) # More efficient version.
测试
我们要 ls
两个文件:一个存在 (myfile
) 和一个不存在 (asdfjasdkfl
)。
$ touch myfile
$ time_info=$( { time ls myfile asdfjasdkfl; } 2>&1 >/dev/null)
$ echo "$time_info"
ls: cannot access asdfjasdkfl: No such file or directory
real 0m0.003s
user 0m0.000s
sys 0m0.000s
命令:
variable=$(time fun)
示例:
var=$(time ls -l) ## or var="$(time ( ls -l ) 2>&1 >/dev/null )"
echo "$var"
输出:
##displays output of ls command and the time taken
real 0m0.003s
user 0m0.001s
sys 0m0.001s
替代方法:
直接在脚本的执行语句上使用time
即可。
示例:time ./fun
我有以下问题需要您的帮助来解决。
我有一个函数可以称之为 "fun"
,我想计算函数需要多少时间 运行,所以我在脚本中添加了这一行:
time fun;
所以像这样,它还会打印函数 运行 所需的时间。重点是我想将 time
的输出重定向到一个变量中,这样我可以稍后根据需要对其进行操作。我已经尝试失败了:
TIME=`time fun`
time fun | tail -3
etc..
有谁知道如何做到这一点,例如,期望的结果是:
somehow add the time output in TIME variable.
所以如果我愿意 echo $TIME
我会得到这样的结果,
real 0m0.45s
user 0m0.35s
sys 0m0.00s
感谢您的宝贵时间!
P.S.
我 运行 Oracle solaris 系统上的 ksh 脚本。
您可以使用 How can I redirect the output of 'time' to a variable or file? 描述的内容:
your_time=$( { time fun ; } 2>&1 >/dev/null)
在这里,我们将 stdout 重定向到 /dev/null
,这样我们就可以摆脱它,只获取 stderr。这是一个特例:
foo=$( { time ls; } 2>&1 ) # More efficient version.
测试
我们要 ls
两个文件:一个存在 (myfile
) 和一个不存在 (asdfjasdkfl
)。
$ touch myfile
$ time_info=$( { time ls myfile asdfjasdkfl; } 2>&1 >/dev/null)
$ echo "$time_info"
ls: cannot access asdfjasdkfl: No such file or directory
real 0m0.003s
user 0m0.000s
sys 0m0.000s
命令:
variable=$(time fun)
示例:
var=$(time ls -l) ## or var="$(time ( ls -l ) 2>&1 >/dev/null )"
echo "$var"
输出:
##displays output of ls command and the time taken
real 0m0.003s
user 0m0.001s
sys 0m0.001s
替代方法:
直接在脚本的执行语句上使用time
即可。
示例:time ./fun