如何存储“time"输出的子串?bash 脚本中的函数 [英] How to store a substring of the output of "time" function in bash script

查看:9
本文介绍了如何存储“time"输出的子串?bash 脚本中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以bash的内置时间函数应该以这种格式输出

So the built-in time function for bash should output in this format

real 0m0.002s
user 0m0.001s
sys  0m0.000s

我想以毫秒为单位保存用户时间,比如 001 有什么干净的方法可以做到这一点?

I want to save the user time in milliseconds, like 001 what's a clean way to do this?

推荐答案

干净的方法是使用 TIMEFORMAT shell 变量只打印用户信息.(man bash 了解更多详情.)

The clean way is to use the TIMEFORMAT shell variable to only print the user information. (man bash for more details.)

然后,当然您需要从中捕获输出.这是不可能从管道中完成的,因为它是由 shell 在内部完成的,但是您可以在子 shell 中运行它,并且输出将转到标准错误.但是你必须以某种方式将命令的输出重定向到其他地方.在这里,我只是放弃了它,但存在许多其他可能性,具体取决于您需要做什么.然后你需要将 d.ddd 转换成 dddd.只需删除句点即可.

Then, of course you need to capture the output from it. This is impossible to do from the pipeline, as it's done internally by the shell, but you can run it in a subshell, and the output will go to standard error. But then you have to somehow redirect the output of the command elsewhere. Here, I just discard it, but many other possibilities exist, depending on exactly what you need to do. Then you need to munge d.ddd into dddd. Just deleting the period will do so.

(TIMEFORMAT="%U"; time ls > /dev/null) |& tr -d .

如果您愿意,可以添加|sed s/^0*// 消除前导零.

If you like, you can add | sed s/^0*// to eliminate the leading zeroes.

%R 将给出实时时间,%S 系统时间.您可以使用例如更改精度%6U 以获得微秒,尽管大多数系统不会接近那么准确.

%R will give real time, %S system time. You can change the precision with e.g. %6U to get microseconds, though most systems won't be anywhere near that accurate.

man bash 获取有关重定向的帮助.man trman sed 获取有关如何使用它们的帮助.

man bash for help on redirections. man tr and man sed for help on how to use them.

这篇关于如何存储“time"输出的子串?bash 脚本中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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