i am having trouble with timing two methods that are included inside multiple for
. I am using System.currentTimeMillis();
. The problem is that i don't know where to put start time and end time. I want to time 5 executions of methodA and methodB.
When i run it i get 12 ms
for methodA and 0ms
for methodB but the program takes about 10 minutes to run. The code is like below:
int count = 0;
double e = 0.3;
long startTimeA;
long endTimeA;
long startTimeB;
long endTimeB;
long sumA = 0;
long sumB = 0;
for(int k=0; k<5; k++){
startTimeA = System.currentTimeMillis();
startTimeB = System.currentTimeMillis();
for(int i = 0; i < 40; i++) {
for(int j = i + 1; j < 40; j++) {
double a = methodA();
endTimeA = System.currentTimeMillis() - startTimeA;
double b = methodB();
endTimeB = System.currentTimeMillis() - startTimeB;
int c = methodC();
}
sumA += endTimeA;
sumB += entTimeB;
}
}
System.out.println("total time A: " + sumA + " ms");
System.out.println("total time B: " + sumB + " ms");
You should read about the
micro-benchmarking
and how to do it in practice.Here is a way to accomplish what you are trying to do: