Skip to content

Instantly share code, notes, and snippets.

@knadh
Last active April 20, 2024 06:35
Show Gist options
  • Star 49 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save knadh/123bca5cfdae8645db750bfb49cb44b0 to your computer and use it in GitHub Desktop.
Save knadh/123bca5cfdae8645db750bfb49cb44b0 to your computer and use it in GitHub Desktop.
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.

@junguler
Copy link

junguler commented Nov 4, 2023

here is my idea of a simple prompt with random colors and also a slightly modified way of showing the numbers, having a 2 part place holder prompt when starting zsh and a 3 part prompt with elapsed time, also includes black and white part for error-ed out commands

had some help from here for making the random colors in the function part of the prompt work

PROMPT='%F{$(($RANDOM%6+1))}[%f%D{%H:%M}%F{$(($RANDOM%6+1))}] %F{$(($RANDOM%6+1))}[%f$(shrink_path -f)%F{$(($RANDOM%6+1))}]%f '

function preexec() {
  timer=$(date +%s%3N)
}

function precmd() {
  if [ $timer ]; then
    local now=$(date +%s%3N)
    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 elapsed=(${h}h ${m}m)
    elif ((m > 0)); then elapsed=(${m}m ${s}s)
    elif ((s >= 10)); then elapsed=${s}.$((ms / 100))s
    elif ((s > 0)); then elapsed=${s}.$((ms / 10))s
    else elapsed=${ms}ms
    fi

	psvar=("$(shrink_path -f)" "$elapsed" "[" "]")
	local ok="%F{$((RANDOM%6+1))}%3v%f%D{%H:%M}%F{$((RANDOM%6+1))}%4v %F{$((RANDOM%6+1))}%3v%f%1v%F{$((RANDOM%6+1))}%4v %F{$((RANDOM%6+1))}%3v%f%2v%F{$((RANDOM%6+1))}%4v%f "
	local err="%K{7}%F{0}%3v%D{%H:%M}%4v%k %K{7}%3v%1v%4v%k %K{7}%3v%2v%4v%k%f "
	PROMPT="%(?.$ok.$err)"

    unset timer
  fi
}

@akhildevelops
Copy link

Shows execution time at the end of the prompt

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

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

    export PROMPT="$OG_PROMPT%F{cyan}${elapsed}ms %{$reset_color%}> "
    unset timer
  fi
}

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