如何使用反引号捕获 time(1) 的经过时间输出? [英] How do I use backticks to capture the elapsed time output from time(1)?

查看:27
本文介绍了如何使用反引号捕获 time(1) 的经过时间输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 time 使用以下命令.我唯一想要的是得到经过的时间,但我什么也得不到.

I’m trying to get the output from time with the following command. The only thing that I want is get the elapsed time, but I get nothing.

$result = `/usr/bin/time -f %e "./"$PROG > /dev/null`;
print $result;

推荐答案

所需的重定向有点棘手.

The redirection needed is just a bit tricky.

my $result = `/usr/bin/time -f %e "./"$PROG 2>&1 >/dev/null`;

time 输出对标准错误(文件描述符 2)的测量,但 Perl 反引号捕获标准输出(文件描述符 1).将上面的重定向序列解读为首先将标准错误发送到标准输出的目的地,然后丢弃原始标准输出."

time outputs its measurement on the standard error (file descriptor 2), but Perl backticks capture the standard output (file descriptor 1). Read the redirection sequence above as "first send the standard error to the standard output’s destination and then throw away the original standard output."

如何从外部命令捕获 STDERR? Perl 常见问题解答中解决了您所看到的问题.

The answer to How can I capture STDERR from an external command? in the Perl FAQ addresses the issue you’re seeing.

捕获命令的STDERR但丢弃它的STDOUT:

To capture a command’s STDERR but discard its STDOUT:

$output = `cmd 2>&1 1>/dev/null`;           # either with backticks
$pid = open(PH, "cmd 2>&1 1>/dev/null |");  # or with an open pipe
while (<PH>) { }                            #    plus a read

... 在所有这些例子中,排序都很重要.这是因为 shell 严格按照从左到右的顺序处理文件描述符重定向.

… Ordering is important in all these examples. That’s because the shell processes file descriptor redirections in strictly left to right order.

system("prog args 1>tmpfile 2>&1");
system("prog args 2>&1 1>tmpfile");

第一个命令将标准输出和标准错误发送到临时文件.第二个命令只将旧标准输出发送到那里,旧标准错误显示在旧标准输出上.

The first command sends both standard out and standard error to the temporary file. The second command sends only the old standard output there, and the old standard error shows up on the old standard out.

请注意,$result 将包含一个尾随换行符,您可以使用 chomp 将其删除,如

Note that $result will contain a trailing newline, which you can remove with chomp as in

chomp $result;

或全部在一行中

chomp(my $result = `/usr/bin/time -f %e "./"$PROG 2>&1 >/dev/null`);

这篇关于如何使用反引号捕获 time(1) 的经过时间输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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