How to time command execution in zsh

| 3 Comments | No TrackBacks

Often I want to know how long it took for a particular command to finish.

An obvious solution to use the time(1) command does not work without a degree of anticipation on my part that I do not normally posess.

At some point I became sufficiently annoyed to actually add some hooks to my .zshrc. All commands executed in an iteractive shell are timed, but the reporting is done only for those that took longer than 10 seconds to execute.

This ugly code does the job:

note_remind=0
note_ignore="yes"
note_command="?"

note_report()
{
    echo ""
    echo "note_report: $note_command completed in $1 seconds"
}

preexec()
{
    if [ "x$TTY" != "x" ]; then
        note_remind="$SECONDS"
        note_ignore=""
        note_command="$2"
    fi
}

precmd()
{
    local xx
    if [ "x$TTY" != "x" ]; then
        if [ "x$note_ignore" = "x" ]; then
            note_ignore="yes"
            xx=$(($SECONDS-$note_remind))
            if [ $xx -gt 10 ]; then
                if [ $TTYIDLE -gt 10 ]; then
                    note_report $xx
                fi
            fi
        fi
    fi
}

Enjoy.

No TrackBacks

TrackBack URL: http://blog.tobez.org/cgi-bin/mt/mt-tb.cgi/74

3 Comments

Thanks. this is just what I was looking for!

What about export REPORTTIME=10 ?

Gyom,

Cool, I did not know about REPORTTIME.

That said, if what one is interested in is the wall
clock, REPORTTIME would not do the trick. But
for many cases when time reporting is actually
useful, REPORTTIME is better than my horrible hack.

Leave a comment

About this Entry

This page contains a single entry by tobez published on March 19, 2009 7:55 PM.

Heart-attack date (mis)calculation was the previous entry in this blog.

Books giveaway is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.