Skip to content

Instantly share code, notes, and snippets.

@knadh
Last active June 24, 2023 15:30
  • Star 42 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Elapsed and execution time for commands in ZSH

Elapsed and execution time display for commands in ZSH

Append this to your ~/.zshrc file.

function preexec() {
  timer=$(($(date +%s%0N)/1000000))
}

function precmd() {
  if [ $timer ]; then
    now=$(($(date +%s%0N)/1000000))
    elapsed=$(($now-$timer))

    export RPROMPT="%F{cyan}${elapsed}ms %{$reset_color%}"
    unset timer
  fi
}

Remixed from @adri's snippet.

@varalgit
Copy link

varalgit commented Mar 14, 2023

I wanted slightly more accuracy, and the time on the left of the normal prompt, so I've changed the code of rafbm to this (works on macos 13):

myprompt="%B%F{cyan}%n@%m:%d/ %h%(!.#.>)%f%b"

function preexec() {
  timer=$(print -P %D{%s%3.})
}

function precmd() {
  timeprompt=""	
  if [ $timer ]; then
    now=$(print -P %D{%s%3.})
    local d_ms=$(($now - $timer))
    local d_s=$((d_ms / 1000))
    local ms=$((d_ms % 1000))
    local s=$((d_s % 60))
    local m=$(((d_s / 60) % 60))
    local h=$((d_s / 3600))

    if   ((h > 0)); then timeprompt=${h}h${m}m${s}s
    elif ((m > 0)); then timeprompt=${m}m${s}.$(printf $(($ms / 100)))s # 1m12.3s
    elif ((s > 9)); then timeprompt=${s}.$(printf %02d $(($ms / 10)))s # 12.34s
    elif ((s > 0)); then timeprompt=${s}.$(printf %03d $ms)s # 1.234s
    else timeprompt=${ms}ms
    fi
    timeprompt="%B%F{yellow}${timeprompt} %f%b"
    unset timer
  fi
  export PS1=${timeprompt}${myprompt}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment