Can I profile my .zshrc/.zshenv?

老子叫甜甜 提交于 2019-11-29 20:15:31

Try adding this at the beginning of the file:

# set the trace prompt to include seconds, nanoseconds, script name and line number
# This is GNU date syntax; by default Macs ship with the BSD date program, which isn't compatible
PS4='+$(date "+%s:%N") %N:%i> '
# save file stderr to file descriptor 3 and redirect stderr (including trace 
# output) to a file with the script's PID as an extension
exec 3>&2 2>/tmp/startlog.$$
# set options to turn on tracing and expansion of commands contained in the prompt
setopt xtrace prompt_subst

and this at the end:

# turn off tracing
unsetopt xtrace
# restore stderr to the value saved in FD 3
exec 2>&3 3>&-

And you should get a detailed log showing the epoch_second.nanosecond time of the execution of each line. Note that GNU date (and OS support) is required to have nanosecond output.

Edit:

added comments

Edit 2:

If you have zsh 4.3.12 or later, you should be able to set PS4 like this instead of using the date command:

zmodload zsh/datetime
setopt promptsubst
PS4='+$EPOCHREALTIME %N:%i> '

which should work on both Linux and OS X to give you nanosecond precision.

You can start your timer at the first suspicious point in your ~/.zshrc (or at the beginning):

integer t0=$(date '+%s')  # move this around
... maybe something suspect ...

# End of zshrc
function {
    local -i t1 startup
    t1=$(date '+%s')
    startup=$(( t1 - t0 ))
    [[ $startup -gt 1 ]] && print "Hmm, poor shell startup time: $startup"
}
unset t0

This alerts me if ever I see a too-slow startup, and I leave it in as a permanent wrapper.

For more sophisticated measurements, there is a zsh module called zprof. It's as simple as temporarily wrapping the contents of your ~/.zshrc in a zmodload zsh/zprof and zprof. This will dump some verbose profiling tables that are easy enough to interpret.

More info in zshmodules(1) manpage.

When I find things that are particularly slow (rbenv init, vcs_info check-for-changes, antigen, nvm, zsh-mime-setup, interpreter version checking, etc) I add SLOW comments as reminders, and try to find workarounds. Slow startups can cause a lot grief, so I tend to avoid zsh packages/framewords whose inner workings I don't grok. compinit is the slowest thing I'm willing to live with and is ~half of total startup time.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!