时间命令自定义格式 [英] Custom format for time command

查看:150
本文介绍了时间命令自定义格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用时间 bash脚本以计算脚本的运行时间和写入日志文件的命令。我只需要在实时,而不是用户和sys。另外还需要在一个体面的格式。例如00:00:00:00(不喜欢标准输出)。我AP preciate任何建议。

I'd like to use the time command in a bash script to calculate the elapsed time of the script and write that to a log file. I only need the real time, not the user and sys. Also need it in a decent format. e.g 00:00:00:00 (not like the standard output). I appreciate any advice.

本来预期格式为 00:00:00.0000 (毫秒)[时间]:[分钟]:[秒] [毫秒]

The expected format supposed to be 00:00:00.0000 (milliseconds) [hours]:[minutes]:[seconds].[milliseconds]

我已经3个脚本。我看到了一个这样的例子:

I've already 3 scripts. I saw an example like this:

{ time { # section code goes here } } 2> timing.log

不过,我只需要在实时性,而不是用户和sys。另外还需要在一个体面的格式。例如 00:00:00:00 (不喜欢标准输出)

在换句话说,我想知道如何把时间输出到工艺的东西更容易。

In other words, I'd like to know how to turn the time output into something easier to process.

推荐答案

您可以使用日期命令前,完成工作后能得到当前的时间要定时并计算这样的区别是:

You could use the date command to get the current time before and after performing the work to be timed and calculate the difference like this:

#!/bin/bash

# Get time as a UNIX timestamp (seconds elapsed since Jan 1, 1970 0:00 UTC)
T="$(date +%s)"

# Do some work here
sleep 2

T="$(($(date +%s)-T))"
echo "Time in seconds: ${T}"

printf "Pretty format: %02d:%02d:%02d:%02d\n" "$((T/86400))" "$((T/3600%24))" "$((T/60%60))" "$((T%60))""

注意:
$((...))可用于基本的算术中的庆典的&ndash的;注意:不要把空格减去之前的 - ,因为这可能会间preTED作为命令行选项

Notes: $((...)) can be used for basic arithmetic in bash – caution: do not put spaces before a minus - as this might be interpreted as a command-line option.

另请参阅: http://tldp.org/LDP/abs/html/arithexp.html

编辑:的结果
此外,你可能想看看 SED 搜索并从生成的输出中提取子的时间

编辑:

例与毫秒时间(实际上纳秒,但截断至毫秒这里)。你的日期的版本有支持%N 格式和庆典应该支持大量涌现。

Example for timing with milliseconds (actually nanoseconds but truncated to milliseconds here). Your version of date has to support the %N format and bash should support large numbers.

# UNIX timestamp concatenated with nanoseconds
T="$(date +%s%N)"

# Do some work here
sleep 2

# Time interval in nanoseconds
T="$(($(date +%s%N)-T))"
# Seconds
S="$((T/1000000000))"
# Milliseconds
M="$((T/1000000))"

echo "Time in nanoseconds: ${T}"
printf "Pretty format: %02d:%02d:%02d:%02d.%03d\n" "$((S/86400))" "$((S/3600%24))" "$((S/60%60))" "$((S%60))" "${M}"

免责声明:结果
我原来的版本说

DISCLAIMER:
My original version said

M="$((T%1000000000/1000000))"

但被剪辑掉,因为它显然没有对某些人的工作,而新版本的报道一样。因为我认为你必须使用的唯一剩下的,但被多数票否决我不同意这一点。结果
选择任何适合你。

but this was edited out because it apparently did not work for some people whereas the new version reportedly did. I did not approve of this because I think that you have to use the remainder only but was outvoted.
Choose whatever fits you.

这篇关于时间命令自定义格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆