Skip to content

Instantly share code, notes, and snippets.

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
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))

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

Remixed from @adri's snippet.

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() {
  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
    timeprompt="%B%F{yellow}${timeprompt} %f%b"
    unset timer
  export PS1=${timeprompt}${myprompt}

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