bash 如何在管道中使用 GNU Time

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13294554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:44:54  来源:igfitidea点击:

how to use GNU Time with pipeline

bashtimegnupipeline

提问by stderr

I want to measure the running time of some SQL query in postgresql. Using BASH built-in time, I could do the following:

我想测量 postgresql 中某些 SQL 查询的运行时间。使用 BASH 内置时间,我可以执行以下操作:

$ time (echo "SELECT * FROM sometable" | psql)

I like GNU time, which provides more formats. However I don't know how to do it with pipe line. For simplicity, I use ls | wcin the following examples:

我喜欢 GNU 时间,它提供了更多的格式。但是我不知道如何用管道来做到这一点。为简单起见,我ls | wc在以下示例中使用:

$ /usr/bin/time -f "%es" (ls | wc)                                                      
-bash: syntax error near unexpected token `('

$ /usr/bin/time -f "%es" "ls | wc"                                                  
/usr/bin/time: cannot run ls | wc: No such file or directory

If I do not group the pipe in any way, it does not complains:

如果我不以任何方式对管道进行分组,它不会抱怨:

$ /usr/bin/time -f "%es" ls | wc       
0.00s

But apparently, this only measure the first part of the pipe, as showing in the next example

但显然,这只测量管道的第一部分,如下例所示

$ /usr/bin/time -f "%es" ls | sleep 20                                                  
0.00s 

So the question is what is the correct syntax for GNU Time with pipe line?

所以问题是带有管道的 GNU Time 的正确语法是什么?

采纳答案by Brian Campbell

Call the shell from time:

time以下位置调用外壳:

/usr/bin/time -f "%es" bash -c "ls | wc"

Of course, this will include the shell start-up time as well; it shouldn't be too much, but if you're on a system that has a lightweight shell like dash(and it's sufficient to do what you need), then you could use that to minimize the start-up time overhead:

当然,这也包括 shell 启动时间;它不应该太多,但是如果您在一个具有轻量级外壳的系统上dash(并且足以执行您需要的操作),那么您可以使用它来最小化启动时间开销:

/usr/bin/time -f "%es" dash -c "ls | wc"

Another option would be to just time the command you are actually interested in, which is the psqlcommand. timewill pass its standard input to the program being executed, so you can run it on just one component of the pipeline:

另一种选择是对您真正感兴趣的命令计时,即psql命令。time将其标准输入传递给正在执行的程序,因此您可以仅在管道的一个组件上运行它:

echo "SELECT * FROM sometable" | /usr/bin/time -f "%es" psql

回答by choroba

Create a script that calls your pipeline. Then

创建一个调用您的管道的脚本。然后

/usr/bin/time -f '%es' script.sh