CSC352: Using Bash Scripts to Measure Program Execution Time
(Redirected from CSC352: Using Bash, an example)
--D. Thiebaut (talk) 13:41, 11 September 2013 (EDT)
This page illustrates how to use a Bash script to run a Java program multiple times while passing it a different parameter every time.
Contents
A simple Java Program
Note that the program gets the value of the variable N from the command line.
class PrintN {
public static void main( String[] args ) {
int N = Integer.parseInt( args[0] );
System.out.println( "I got " + N );
}
}
Running the program 10 times from the command line
- Running the program above 10 times can be done as follows, from the command line:
bash javac PrintN.java for i in 1 2 3 4 5 6 7 8 9 10 ; do java PrintN $i done
Running the program from a Bash script
The script is shown below:
#! /bin/bash # runPrintN.sh # javac PrintN.java for i in 1 2 3 4 5 6 7 8 9 10 ; do java PrintN $i done
Make sure you make the script executable before you call it:
chmod a+x runPrintN.sh
You can now run the program 10 times with just one command:
./runPrintN.sh I got 1 I got 2 I got 3 I got 4 I got 5 I got 6 I got 7 I got 8 I got 9 I got 10
Measuring the Execution Time of the Program
- An easy way to measure the execution time of each time we run the program is to use the time Linux command, as illustrated below:
#! /bin/bash # runPrintN.sh # javac PrintN.java for i in 1 2 3 4 5 6 7 8 9 10 ; do #java PrintN $i time java PrintN $i done
- Note that Linux also supports another time command, located in /usr/bin. It gives more information in a less readable format:
#! /bin/bash # runPrintN.sh # javac PrintN.java for i in 1 2 3 4 5 6 7 8 9 10 ; do #java PrintN $i /usr/bin/time java PrintN $i done