Last Updated: July 14, 2017
·
9.916K
· adri

ZSH: Display commands runtime in prompt

Hi Shellers,

Development speed matters to many programmers, which is why I like to keep an eye on how long commands run:

If you use ZSH, paste this in your startup script, I put it in .zsh.after/prompt.zsh. It adds the run time of the last command in seconds to your right command prompt.

function preexec() {
  timer=${timer:-$SECONDS}
}

function precmd() {
  if [ $timer ]; then
    timer_show=$(($SECONDS - $timer))
    export RPROMPT="%F{cyan}${timer_show}s %{$reset_color%}"
    unset timer
  fi
}

In case you don't use ZSH, see this script which emulates above functions in bash. You need to add a preexec_install after you define above functions.

2 Responses
Add your response

This keeps the time of the last executed command on the right when you press Enter. Is there a way to replace that with the time elapsed since the last command?

In bash, this did the trick:

trap 'SECONDS=0' DEBUG
PS1='... [${SECONDS}s] ... $ '

But in zsh, $SECONDS is always zero.

over 1 year ago ·

Really useful, more useful than my current approach that displays end-time instead of duration. Still is has a breaking bug: when you move cursor back for a wrapped prompt line (long) it will mess the row making it impossible to use.

over 1 year ago ·