Command Timing in ZSH

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))

		RPROMPT="%F{cyan} $(converts "$elapsed") %{$reset_color%}"
		export RPROMPT
		unset timer

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"
	if [[ $h -gt 0 ]]; then
			echo -n " ${h}h"
	if [[ $m -gt 0 ]]; then
			echo -n " ${m}m"
	if [[ $s -gt 0 ]]; then
		echo -n " ${s}s"
	if [[ $ms -gt 0 ]]; then
		echo -n " ${ms}ms"
}Code language: PHP (php)

Other Posts Not Worth Reading

Hey, You!

Like this kind of garbage? Subscribe for more! I post like once a month or so, unless I found something interesting to write about.


Leave a Reply