In: Computer Science
public static int example3
(int [] arr ) {
int n = arr.length , total = 0;
for (int j = 0; j < n ; j += 2)
for (int k = 0; k <= j ; k ++)
total += arr [ j ]; return total ;
}
what is the running time of this method?
The time taken by a function in Java can be calculated with the help of java.lang.System.currentTimeMillis() method. which returns the current time in millisecond. By calling this method at the beginning and at the end of function and by taking the difference we measure the time taken by the function. The given program calculates the running time of example3() method by taking an array of size 'n' and each element=1000.
import java.io.*;
public class Time {
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n, i, r;
System.out.println("Enter the size of array");
n=Integer.parseInt(br.readLine());
int a[]=new int[n];
for(i=0; i<n; i++)
{
a[i]=1000;
}
long s = System.currentTimeMillis(); // Starting of the function
r=example3(a);
long e = System.currentTimeMillis(); // ending of the function
System.out.println("The running time of method example3() is " +
(e - s) + " ms");
}
public static int example3(int [] arr ) // function whose running time is to be calculated
{
int n = arr.length , total = 0;
for (int j = 0; j < n ; j += 2)
for (int k = 0; k <= j ; k ++)
total += arr [ j ];
return total ;
}
}
Output:
Enter the size of array
10000
The running time of method example3() is 22 ms