64

I would like to make a script that outputs only the real time value from the time command so I can plot the results. For example time command outputs

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

I want to write a script that outputs

60.001 

How do I get just real time value from 'time' command in seconds?

Matthew Sowders
  • 1,640
  • 1
  • 19
  • 32

4 Answers4

83

If you're using the Bash builtin time, set the TIMEFORMAT variable to %R:

$ TIMEFORMAT=%R
$ time sleep 1
1.022
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
  • 5
    Thanks! I like `%0lR` best (more readable) for slow-executing commands ( see http://stackoverflow.com/questions/3683434/custom-format-for-time-command/3686395#3686395 ) – qubodup Oct 17 '16 at 00:03
  • 5
    `unset TIMEFORMAT` to get back the original formating – Boris Verkhovskiy Aug 14 '18 at 04:08
  • rather than unset afterwords, I'd suggest `TIMEFORMAT=%R time sleep 1` per https://unix.stackexchange.com/a/126942 but I just confirmed that it fails, presumably because time "forwards" somehow those declarations to the command, not to time. – mellow-yellow Jun 01 '22 at 19:05
  • 1
    @mellow-yellow: `time` isn't a command. It's referred to in the Bash manual as a reserved word. It is processed specially. – Dennis Williamson Jun 23 '22 at 19:10
47

time can take an optional --format or -f parameter, but you have to use the full path to the time command, /usr/bin/time

/usr/bin/time -f "%e" sleep 3

3.00

Without the path, it'll use the time command of the shell which just treats all arguments as the command, so you'll get an -f: command not found.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
eumiro
  • 207,213
  • 34
  • 299
  • 261
  • 2
    @frederik-b it doesn't on Ubuntu 19.04 `\time -f "%e" sleep 5` tells me that `bash: time: command not found` – Boris Verkhovskiy Oct 11 '19 at 16:20
  • 2
    This works with gnu time directly, but not shell's built in time commands, if you run `which -a time` you may see the shell's is preferred, this is why using the full path to the binary works in some cases. – Keith Smiley Apr 16 '20 at 17:36
4

If you write \time you enforce not to use the bash built in time. So with \time -f '%e' command you are done.

Martin T.
  • 505
  • 5
  • 10
0

Alternatively, use /usr/bin/time or take a look at the similar question
Using time command in bash script.

Community
  • 1
  • 1
Arc
  • 11,143
  • 4
  • 52
  • 75