Sunday, March 2, 2008

Understand your code's performance using time command - BASH


time - run programs and summarize system resource usage

The time command is useful to measure/understand your code's performance. The usual output consists of real, user and system time.
Real time is the amount of time between when the code started and when it exited.
User time and system time are the amount of time spent executing application code versus kernel code, respectively.

Two types of time command are available.

Shell's in-build time: Gives only scheduler information
/usr/bin/time: Gives more information, also allows formatting the output

To save the "time" details in a file:
$ /usr/bin/time -p ./chess.sh 2> time.out

Illustrating the use of "time" command with an example below:

I have two scripts for the same purpose(subdividing a file - sending each line to a new file named as the line-number, also adding a line called HEADER as first line of the

files, and a blank line as the last or 3rd line), but written in two different ways.
Now to compare the performance of the two scripts:

$ cat way1.sh
#!/bin/sh
awk '{print "HEADER" > "file_" NR} {print > "file_" NR} {printf("\n") > "file_" NR}' thefile.out


$ cat way2.sh
#!/bin/sh
cat thefile.out | awk '{ print "HEADER"
printf("%s\n",$0)
print "" }' | awk '{print >("file_" int((NR+2)/3))}'


$ time ./way1.sh
real 0m0.130s
user 0m0.060s
sys 0m0.107s

$ time ./way2.sh
real 0m0.178s
user 0m0.152s
sys 0m0.091s

So way2.sh is a bit expensive performance wise compared to way1.sh.

No comments:

© Jadu Saikia www.UNIXCL.com