Tuesday, November 10, 2015

Calculating elapsed time in shell scripts

Trying to figure out what part of a shell script is taking too long can be a frustrating experience since there isn't a simple command to give you a monotonic, fine grained measure of time. But with the little program in my previous post (http://leavingwithnothing.blogspot.com/2015/11/gethrtime-on-linux.html) you can use the following shell script routines:
#!/bin/bash

ts() {
        /root/gethrtime
}

start() {
        start=$(ts)
}

elapse() {
        echo "Runtime: " $(($(ts) - $start))
}
Here's an example of how to use them:
#!/bin/bash

start
df -kh
elapse
Which outputs:
root@foo # ./elapsed_df.sh
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda2        15G  3.0G   11G  22% /
none            4.0K     0  4.0K   0% /sys/fs/cgroup
udev            3.9G  4.0K  3.9G   1% /dev
tmpfs           797M  1.4M  796M   1% /run
none            5.0M     0  5.0M   0% /run/lock
none            3.9G     0  3.9G   0% /run/shm
none            100M     0  100M   0% /run/user
Runtime: 13593073

No comments:

Post a Comment