Skip to content

Instantly share code, notes, and snippets.

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.

@kimonoki

This comment has been minimized.

Copy link

kimonoki commented May 18, 2019

I get preexec:1: bad math expression: operator expected at `N/1000000'

@jep-dev

This comment has been minimized.

Copy link

jep-dev commented Jul 13, 2019

Just thought I'd post my 2 cents. I think you want date +%s%0N over date+%s%N, unless I'm missing something; otherwise nanoseconds are printed by %N without leading zeroes, independently of the %s. If you're using nanos as fractional seconds (aka fixed point arithmetic with ns as the atomic unit) the leading zeroes become significant. So for example, 1s+108ns = "1100000000", 1s+107ns = "110000000", ..., 1s+1ns = "11". (You want 1s+108ns = "1100000000", 1s+107ns = "1010000000", ..., 1s+1ns = "1000000001".) You can expect 10% of measurements to have at least 1 leading zero in the nanos, and each omitted zero to cause an order of magnitude of error in the total time. Hope this helps!

@knadh

This comment has been minimized.

Copy link
Owner Author

knadh commented Jul 14, 2019

@jep-dev You're right. Updated the gist. Thank you.

@knadh

This comment has been minimized.

Copy link
Owner Author

knadh commented Jul 14, 2019

@kimonoki Sorry, missed your comment. Unsure about the error.

@rufreakde

This comment has been minimized.

Copy link

rufreakde commented Aug 13, 2019

@kimonoki Getting the same error:
bad math expression: operator expected at 'N/1000000'

timer=$(($(date +%s%0N)/1000000)) - error
$(($(date +%s)/1000000)) - no error

I am not sure here myself using only %s instead of %s%0N does work for me but nanoseconds throws an error...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.