timer.plugin.zsh 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. zmodload zsh/datetime
  2. __timer_current_time() {
  3. zmodload zsh/datetime
  4. echo $EPOCHREALTIME
  5. }
  6. __timer_format_duration() {
  7. local mins=$(printf '%.0f' $(($1 / 60)))
  8. local secs=$(printf "%.${TIMER_PRECISION:-1}f" $(($1 - 60 * mins)))
  9. local duration_str=$(echo "${mins}m${secs}s")
  10. local format="${TIMER_FORMAT:-/%d}"
  11. echo "${format//\%d/${duration_str#0m}}"
  12. }
  13. __timer_save_time_preexec() {
  14. __timer_cmd_start_time=$(__timer_current_time)
  15. }
  16. __timer_display_timer_precmd() {
  17. if [ -n "${__timer_cmd_start_time}" ]; then
  18. local cmd_end_time=$(__timer_current_time)
  19. local tdiff=$((cmd_end_time - __timer_cmd_start_time))
  20. unset __timer_cmd_start_time
  21. if [[ -z "${TIMER_THRESHOLD}" || ${tdiff} -ge "${TIMER_THRESHOLD}" ]]; then
  22. local tdiffstr=$(__timer_format_duration ${tdiff})
  23. local cols=$((COLUMNS - ${#tdiffstr} - 1))
  24. echo -e "\033[1A\033[${cols}C ${tdiffstr}"
  25. fi
  26. fi
  27. }
  28. autoload -U add-zsh-hook
  29. add-zsh-hook preexec __timer_save_time_preexec
  30. add-zsh-hook precmd __timer_display_timer_precmd