26

In bash I am able to write a script that contains something like this:

{ time {

#series of commands
echo "something"
echo "another command"
echo "blah blah blah"

} } 2> $LOGFILE

In ZSH the equivalent code does not work and I can not figure out how to make it work for me. This code works but I don't exactly know how to get it to wrap multiple commands.

{ time echo "something" } 2>&1

I know I can create a new script and put the commands in there then time the execution properly, but is there a way to do it either using functions or a similar method to the bash above?

4 Answers 4

37

Try the following instead:

{ time ( echo hello ; sleep 10s;  echo hola ; ) } 2>&1 
1
  • 2
    You have made my day just that much better. Works as advertised.
    – cldfzn
    Jul 14, 2011 at 13:25
16

If you want to profile your code you have a few alternatives:

  • Time subshell execution like:

    time ( commands ... )

  • Use REPORTTIME to check for slow commands:

    export REPORTTIME=3 # display commands with execution time >= 3 seconds

  • setop xtrace as explained here

  • The zprof module

1
  • REPORTTIME is great for tasks that have taken an unexpectedly long amount of time to run, as you don't have to remember to time it before you start it. It displays the time taken in the same format as time, so is probably using time on every command but only showing the output if the execution time is greater than REPORTTIME.
    – drkvogel
    Apr 11, 2019 at 13:16
2

Try replace { with ( ? I think this should help

1

You can also use the times POSIX shell builtin in conjunction with functions. It will report the user and system time used by the shell and its children. See http://pubs.opengroup.org/onlinepubs/009695399/utilities/times.html

Example:

somefunc() {
    code you want to time here
    times
}

The reason for using a shell function is that it creates a new shell context, at the start of which times is all zeros (try it). Otherwise the result contains the contribution of the current shell as well. If that is what you want, forget about the function and put times last in your script.

1
  • This doesn't seem to work in zsh. The functions don't introduce new contexts there.
    – HappyFace
    Aug 24, 2020 at 23:41

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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