Appearance
macOS 上 zsh 终端启动耗时的问题和解决方法
找到 ~/.zshrc
,其它终端就找对应的启动脚本。
在开头加上一行 zmodload zsh/zprof
,在结尾加上一行 zprof
。这样可以测算出当前启动脚本各项命令的耗时。
sh
num calls time self name
-----------------------------------------------------------------------------------
1) 29 219.34 7.56 67.14% 208.35 7.18 63.77% _omz_source
2) 1 73.99 73.99 22.65% 66.82 66.82 20.45% nvm_auto
3) 2 18.09 9.05 5.54% 18.09 9.05 5.54% compaudit
4) 1 22.54 22.54 6.90% 4.45 4.45 1.36% compinit
5) 1 7.17 7.17 2.19% 4.12 4.12 1.26% nvm_rc_version
6) 1 3.98 3.98 1.22% 3.94 3.94 1.21% _zsh_highlight_load_highlighters
7) 1 3.85 3.85 1.18% 3.85 3.85 1.18% (anon) [/Users/xt/.oh-my-zsh/tools/check_for_upgrade.sh:162]
8) 1 3.41 3.41 1.04% 3.41 3.41 1.04% zrecompile
9) 1 3.03 3.03 0.93% 3.03 3.03 0.93% nvm_echo
10) 1 2.44 2.44 0.75% 2.44 2.44 0.75% test-ls-args
11) 1 6.21 6.21 1.90% 2.36 2.36 0.72% handle_update
12) 3 0.94 0.31 0.29% 0.92 0.31 0.28% add-zle-hook-widget
13) 1 0.92 0.92 0.28% 0.91 0.91 0.28% _zsh_highlight__function_callable_p
14) 1 0.70 0.70 0.21% 0.70 0.70 0.21% @jov.chpwd-git-dir-hook
15) 1 0.69 0.69 0.21% 0.69 0.69 0.21% regexp-replace
16) 12 0.62 0.05 0.19% 0.62 0.05 0.19% add-zsh-hook
17) 1 0.55 0.55 0.17% 0.55 0.55 0.17% colors
18) 15 0.53 0.04 0.16% 0.53 0.04 0.16% compdef
19) 9 0.49 0.05 0.15% 0.49 0.05 0.15% is-at-least
20) 12 0.14 0.01 0.04% 0.14 0.01 0.04% is_plugin
21) 1 0.13 0.13 0.04% 0.13 0.13 0.04% (anon) [/Users/xt/.oh-my-zsh/custom/plugins/zsh-autosuggestions/zsh-autosuggestions.zsh:458]
22) 1 0.09 0.09 0.03% 0.04 0.04 0.01% complete
23) 2 0.02 0.01 0.01% 0.02 0.01 0.01% is_theme
24) 1 0.02 0.02 0.01% 0.02 0.02 0.01% (anon) [/usr/share/zsh/5.9/functions/add-zle-hook-widget:28]
25) 2 0.02 0.01 0.01% 0.02 0.01 0.01% bashcompinit
26) 1 3.05 3.05 0.93% 0.02 0.02 0.01% nvm_err
27) 2 0.02 0.01 0.01% 0.02 0.01 0.01% env_default
28) 1 74.01 74.01 22.65% 0.01 0.01 0.00% nvm_process_parameters
29) 1 0.01 0.01 0.00% 0.01 0.01 0.00% _zsh_highlight__is_function_p
30) 1 0.01 0.01 0.00% 0.01 0.01 0.00% nvm_is_zsh
31) 1 0.00 0.00 0.00% 0.00 0.00 0.00% _zsh_highlight_bind_w
然后对耗时最多的项目进行优化,然后重启 zsh,再重新测试,反复优化,直到满意为止。
排查后发现我的终端主要卡在了 nvm 初始化的脚本,问过 AI 后修改为:
sh
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" --no-use
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"