How to find execution time of a script in Linux ?

Suppose you have created two or three commands that perform same operation and want to know which script takes less time in execution.

For this, we need to identify time taken by each command/script in Linux and then compare them to identify the best script/command.

In this article, we will look at the possible ways to identify the execution time of the command/script in Linux.

1. Using time command

### Lets create a sample file with below contents.
[root@nglinux ~]# cat file1
for i in {1..5}; do echo $i; done

### Lets make the file executable.
### Now lets run time command with file1 as input to know the execution time of the script.
[root@nglinux ~]# chmod +x file1; time ./file1

real	0m0.008s
user	0m0.001s
sys	0m0.005s
[root@nglinux ~]# 

2. Using variable and compare time manually
Another way is to calculate the time manually by storing start and end time in a variable and then compare the time.

### Lets create the file file1 with below contents.
[root@nglinux ~]# cat file1
start=`date +%s`
for i in {1..100000}; do echo $i > /dev/null; done
end=`date +%s`
echo "Time:" $totaltime "s"
[root@nglinux ~]# 

### Execute the script to know the total file execution time in seconds.
[root@nglinux ~]# ./file1 
Time: 6 s

### Compare the output with time command, it is same.
[root@nglinux ~]# time ./file1 
Time: 6 s

real	0m5.779s
user	0m4.607s
sys	0m1.120s

Seems interesting !!! Now you know how to find the execution time of a script in Linux.

Just apply above trick and find out the best script for a particular task in Linux.

Leave a Reply

Your email address will not be published.