Skip to content

Instantly share code, notes, and snippets.

@knadh
Last active April 20, 2023 07:42
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.

@digitaldonkey
Copy link

<3 @mezza

@Joilence
Copy link

Is it possible to add this execution time at the rear of the first line like the style of Spaceship Prompt?

@sudarshan85
Copy link

Dumb question but whats the math for getting this in seconds? Change 1000000 to 1000?

@Sleepful
Copy link

<3 @jututt

@Yanis-F
Copy link

Yanis-F commented May 25, 2022

Dumb question but whats the math for getting this in seconds? Change 1000000 to 1000?

Here is the same snippet as above, but it displays as seconds with 3 decimals

function preexec() {
  timer=$(($(date +%s%0N)*0.000000001))
}

function precmd() {
  if [ $timer ]; then
    now=$(($(date +%s%0N)*0.000000001))
    elapsed=$(echo $(($now-$timer)) | awk '{printf "%.3f", $1}')

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

@varalgit
Copy link

  cmd_start=$(($(print -P %D{%s%6.}) / 1000))

Why not simply use the following?

  cmd_start=$(print -P %D{%s%3.})

No need to ask for microsecs and then divide by 1000, if you can get millisecs directly...

@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