Monday, 12 August 2013

Analysis of execution frequency code

Analysis of execution frequency code

I was trying to find out the frequency of execution of some statements in
the following code.
I wanted to check how many times each for loop was executed for a given
input array.
For this purpose,I added three variables icnt,jcnt and kcnt.
public class FreqCounter{
public static void count1(int[] a){
int N = a.length;
int count = 0;
int icnt = 0;
int jcnt = 0;
int kcnt = 0;
for(int i=0;i<N;i++){
icnt++;
for(int j=i+1;j<N;j++){
jcnt++;
for(int k=j+1; k<N;k++){
kcnt++;
}
}
}
System.out.printf("i loop=%d times\n",icnt);
System.out.printf("j loop=%d times\n",jcnt);
System.out.printf("k loop=%d times\n",kcnt);
}
public static void main(String[] args) {
int N = 100;
int[] a = new int[N];
count1(a);
}
}
I got the following output
i loop=100 times
j loop=4950 times
k loop=161700 times
I tried to analyze this as follows
The outer for loop (i=0 to < N)
This executes N times ,so for N=100 ,the count will be 100
Inner for loop(j=i+1 to < N)
This is equivalent to finding combinations of N elements ,taken 2 at a time
which means C(N,2) = N! /((N-2)! * 2!) = (N *(N-1))/2 = ((N^2)/2)-(N/2)
For N=100 , this will be (100*100/2)-50 = 4950
Innermost loop (k=j+1 to
Equivalent to finding combinations of N elements ,taken 3 at a time
ie, C(N,3) = N!/((N-3)! * 3!) = N*(N-1)*(N-2)/3! = (N^3/6)-(N^2/2)+N/3
For N=100, this will be 100^3/6 - 100^2/2 + 100/3 = 161700
I am getting the correct values,but wanted to know if the
analysis(combinations stuff) is proper.(I have only recently learned the
permutation/combinations lessons).If someone can add more to this
analysis, it would be helpful.

No comments:

Post a Comment