How can I output the real time a command takes (and nothing else)?

Example:

This won't work:

$ time -p sleep 2 | grep real
real 2.00
user 0.00
sys 0.00

I want something like:

$ print-real-time sleep 2
2.00
link|improve this question

38% accept rate
feedback

3 Answers

up vote 4 down vote accepted

You need to capture the output of time first. Then you can process it.

link|improve this answer
Right. The question is how to do that... – user9474 Sep 29 '11 at 18:22
3  
Did you bother read the linked article? – Ignacio Vazquez-Abrams Sep 29 '11 at 18:24
Oh, I didn't see it was a link. Thanks! – user9474 Sep 29 '11 at 18:26
1  
Good solution, note however that the entire world is not running bash... – voretaq7 Sep 29 '11 at 18:27
feedback

A non-BASH-specific solution (explicitly use /usr/bin/time so it's not the pipe-gobbling bash builtin) --

/usr/bin/time -p some_command_or_subshell 2>&1 | grep real | awk '{print $2}'

Depending on the delicate nature of whatever you feed this output to you may want to redirect the output of your subject command to /dev/null...

link|improve this answer
feedback

Here's a hacky solution using cut to split the fields.

time -p sleep 2 | grep real | cut -f2 -d' '

You can also use awk:

time -p sleep 2 | grep real | awk '{ print $2 }'
link|improve this answer
Does that actually work on your system? On mine, it doesn't give the desired output "2.00". – user9474 Sep 29 '11 at 19:12
It works on mine; but it probably also depends on what time command you're running. It sounds like bash behaves differently with this--zsh gives you the output on stdout normally. – Andrew M. Sep 30 '11 at 13:33
@Redmumba this is the principle danger of using shell builtins - they may not work the same way for everyone, and in your case they don't conform to the POSIX standard ( time is supposed to report its output to stderr, not stdout ; cf. pubs.opengroup.org/onlinepubs/9699919799/utilities/time.html ) – voretaq7 Sep 30 '11 at 16:29
Tres bizarre! I guess you learn something new everyday. – Andrew M. Sep 30 '11 at 18:57
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.