使用unix“ time”命令将时间输出到文件,但将命令输出留给控制台

问题描述 投票:0回答:1

我计时一个具有某些输出的命令。我想将time命令的实时输出到文件,但将命令的输出留给控制台。

例如,如果我执行time my_command,则会在控制台中打印出来

several lines of output from my_command ... 
real 1m25.970s
user 0m0.427s
sys 0m0.518s

在这种情况下,我只想将1m25.970s存储到文件,但仍将命令的输出打印到控制台。

shell unix time io-redirection
1个回答
0
投票

time命令很棘手。 time的POSIX规范没有定义默认的输出格式,但是为time(大概是“ POSIX”)选项定义了格式。请注意(不容易理解的)管道中命令序列的讨论。

[Bash规范说-p前缀time,这意味着'pipeline'乘以time cmd1 | cmd2cmd1。它将结果写入标准错误。 Korn外壳类似。

POSIX格式在cmd2之类的标签和时间之间需要一个空格;默认格式通常使用制表符而不是空格。请注意,real命令可能还有另一种输出格式。例如,它在macOS上执行,默认情况下,单行列出3次,时间值后带有标签;它支持/usr/bin/time以近似POSIX格式打印(但标签和时间之间有多个空格)。

您可以轻松地将所有写入标准错误的信息保存到文件中:

-p

如果(time my_command) 2> log.file 或它调用的任何程序将任何错误报告为标准错误,这些错误也将到达日志文件。然后,您将从my_command的所有三行输出写入文件。

如果您的外壳是Bash,则可以使用time过滤某些输出。

我不会在单个命令行中尝试;使它工作所需的象形文字令人毛骨悚然,并且最好封装在shell脚本中。

例如,使用shell脚本process substitution捕获time.filter的输出,仅将time时间写入日志文件(默认为real,可通过提供备用日志文件名作为第一个参数来配置) >

log.file

这假设您的#!/bin/sh output="${1:-log.file}" shift sed -E '/^real[[:space:]]+(([0-9]+m)?[0-9]+[.][0-9]+s?)/{ s//\1/; w '"$output"' d;} /^(user|sys)[[:space:]]+(([0-9]+m)?[0-9]+[.][0-9]+s?)/d' "$@" 使用sed启用扩展的正则表达式。脚本的第一行查找包含-E标签的行及其后的时间(采用多种可能的格式,但不是全部)。它接受可选的分钟值,例如real,或者仅接受秒值60m05.003s,或者仅接受5.00s(POSIX格式-要求小数点后至少一位)。它捕获时间部分并将其打印到所选文件中(默认为5.0;您可以在命令行上将备用名称指定为第一个参数)。注意,即使GNU log.file也会将sed命令之后的所有内容都视为文件名;您必须继续w(删除)命令和右括号d在换行符上。 GNU }sed之后不需要分号; BSD(macOS)d可以。第二行识别并删除seduser次中的报告行。其他所有内容都保持不变。

该脚本处理您在日志文件名之后提供的所有文件,如果不提供,则处理标准输入。更好的命令行符号应使用显式选项(sys)和-l logfile指定日志文件。

有了这个,我们可以设计一个报告标准错误和标准输出的程序-getopts

my_command

您可以使用echo "nonsense: error: positive numbers are required for argument 1" >&2 dribbler -s 0.4 -r 0.1 -i data -t echo "apoplexy: unforeseen problems induced temporary amnesia" >&2 代替cat data命令。如图所示的dribbler命令从dribbler中读取行,并将它们写入标准输出,并在行之间具有高斯分布,并具有随机延迟。平均延迟为0.4秒;标准偏差为0.1秒。其他两行伪装成将错误报告为标准错误的命令。

我的data文件包含一个叫做data的废话“诗”。

有了适当的背景,我们可以运行命令并在'The Great Panjandrum'中捕获实时时间,删除(忽略)用户和系统时间值,同时使用以下命令将其余标准错误发送到标准错误:

log.file

((通常花费的时间在6到8秒之间。共有17行,因此您希望它花费大约6.8秒,每行0.4秒。)空行来自$ (time my_command) 2> >(tee raw.stderr | time.filter >&2) nonsense: error: positive numbers are required for argument 1 So she went into the garden to cut a cabbage-leaf to make an apple-pie and at the same time a great she-bear coming down the street pops its head into the shop What no soap So he died and she very imprudently married the Barber and there were present the Picninnies and the Joblillies and the Garyulies and the great Panjandrum himself with the little round button at top and they all fell to playing the game of catch-as-catch-can till the gunpowder ran out at the heels of their boots apoplexy: unforeseen problems induced temporary amnesia $ cat log.file 0m7.278s $ ;很难删除空白行,而仅删除空白行,尤其是正如POSIX所说的那样,它是可选的。这不值得。

© www.soinside.com 2019 - 2024. All rights reserved.