Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use backticks to capture the elapsed time output from time(1)?

Tags:

time

perl

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;
like image 549
jaumevn Avatar asked Jan 22 '26 21:01

jaumevn


1 Answers

The redirection needed is just a bit tricky.

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

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.”

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

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

… 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.

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

chomp $result;

or all in a single line with

chomp(my $result = `/usr/bin/time -f %e "./"$PROG 2>&1 >/dev/null`);
like image 90
Greg Bacon Avatar answered Jan 24 '26 10:01

Greg Bacon