Just a little question about timing programs on Linux: the time command allows to measure the execution time of a program:
[ed@lbox200 ~]$ time sleep 1
real 0m1.004s
user 0m0.000s
sys 0m0.004s
Which works fine. But if I try to redirect the output to a file, it fails.
[ed@lbox200 ~]$ time sleep 1 > time.txt
real 0m1.004s
user 0m0.001s
sys 0m0.004s
[ed@lbox200 ~]$ cat time.txt
[ed@lbox200 ~]$
I know there are other implementations of time with the option -o to write a file but my question is about the command without those options.
Any suggestions ?
Simple. The GNU
time
utility has an option for that.But you have to ensure that you are not using your shell's builtin
time
command, at least thebash
builtin does not provide that option! That's why you need to give the full path of thetime
utility:If you care about the command's error output you can separate them like this while still using the built-in time command.
or
As you see the command's errors go to a file (since
stderr
is used fortime
).Unfortunately you can't send it to another handle (like
3>&2
) since that will not exist anymore outside the{...}
That said, if you can use GNU time, just do what @Tim Ludwinski said.
Since the output of 'time' command is error output, redirect it as standard output would be more intuitive to do further processing.
Wrap
time
and the command you are timing in a set of brackets.For example, the following times
ls
and writes the result ofls
and the results of the timing intooutfile
:Or, if you'd like to separate the output of the command from the captured output from
time
:I ended up using:
If you don't want to touch the original process' stdout and stderr, you can redirect stderr to file descriptor 3 and back:
You could use that for a wrapper (e.g. for cronjobs) to monitor runtimes: