zsh 中添加命令执行计时

Elapsed and execution time for commands in ZSH

在 ~/.zshrc 文件中添加:

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
}

2025/4/20 缺点:计时显示在一行最后,每次复制终端文本会把这个时间一并复制了,而且这一行相当长导致时间显示在第二行(折行),让人摸不着头脑这个多余的文本是哪里来的。