I’ve had a few snippets in my .zshrc
file for a while now that will output how long a command takes to process.
First off, I’d like to say that I did not come up with this idea, and I didn’t really write the code. I’ve snipped it from somewhere and modified it over time, so I am very sorry to the original author for not being able to give full credit. I didn’t save where I got it from–so if anyone comes across this in the future and might know where the idea came from, drop it in the comments.
Now, on to the fun:
The original script only went down to the second, but I wanted more granularity than that, so I went down to the millisecond.
You’ll likely need to install gdate
(brew install gdate
) for this to work properly.
The code (added to ~/.zshrc
):
function preexec() {
timer=$(($(gdate +%s%0N)/1000000))
}
function precmd() {
if [ "$timer" ]; then
now=$(($(gdate +%s%0N)/1000000))
elapsed=$now-$timer
reset_color=$'\e[00m'
RPROMPT="%F{cyan} $(converts "$elapsed") %{$reset_color%}"
export RPROMPT
unset timer
fi
}
converts() {
local t=$1
local d=$((t/1000/60/60/24))
local h=$((t/1000/60/60%24))
local m=$((t/100/60%60))
local s=$((t/1000%60))
local ms=$((t%1000))
if [[ $d -gt 0 ]]; then
echo -n " ${d}d"
fi
if [[ $h -gt 0 ]]; then
echo -n " ${h}h"
fi
if [[ $m -gt 0 ]]; then
echo -n " ${m}m"
fi
if [[ $s -gt 0 ]]; then
echo -n " ${s}s"
fi
if [[ $ms -gt 0 ]]; then
echo -n " ${ms}ms"
fi
echo
}
Code language: PHP (php)
Leave a Reply