Comparing Execution Times of Different Commands
Now that we understand how to use the time
command and interpret its output, let's compare the execution times of different commands to understand their performance characteristics.
First, let's create an I/O-intensive script that reads and writes data:
echo '#!/bin/bash' > ~/project/io_intensive.sh
echo 'for i in {1..10}; do' >> ~/project/io_intensive.sh
echo ' cat /etc/passwd > ~/project/temp_file_$i.txt' >> ~/project/io_intensive.sh
echo ' cat ~/project/temp_file_$i.txt > /dev/null' >> ~/project/io_intensive.sh
echo 'done' >> ~/project/io_intensive.sh
echo 'rm ~/project/temp_file_*.txt' >> ~/project/io_intensive.sh
echo 'echo "I/O operations complete"' >> ~/project/io_intensive.sh
Make the script executable:
chmod +x ~/project/io_intensive.sh
Now, let's time this I/O-intensive script:
time ~/project/io_intensive.sh
You should see output similar to this:
I/O operations complete
real 0m0.050s
user 0m0.010s
sys 0m0.040s
Notice that the sys
time is now higher relative to the user
time compared to our CPU-intensive script. This is because file I/O operations require system calls, which run in kernel mode.
Let's also time a common Linux command that searches for text patterns:
time grep -r "root" /etc
This command recursively searches for the word "root" in all files under the /etc
directory. The output might look like:
[many matches shown here]
real 0m0.567s
user 0m0.123s
sys 0m0.445s
Now let's compare all three commands we've timed:
simple_echo.sh
: Very quick execution, minimal CPU and system time.
cpu_intensive.sh
: Longer execution, mostly user CPU time.
io_intensive.sh
: Moderate execution time, higher system time due to I/O operations.
grep -r "root" /etc
: Moderate execution time, balanced between user and system time due to both text processing and file I/O.
This comparison demonstrates how different types of operations affect execution time and resource usage. Understanding these patterns can help you identify bottlenecks in your scripts and commands, leading to more efficient code.
For more detailed timing information, you can also use the /usr/bin/time
command with the -v
(verbose) flag:
/usr/bin/time -v ~/project/simple_echo.sh
This provides extensive information about the command's execution, including memory usage, page faults, and more.