In my code, both for
loops have the same time complexity and same operation, however the second nested for
loop takes almost 40 times more time than first one. Why is this happening?
I am using javac compiler and running my code in windows command prompt.
import java.util.concurrent.TimeUnit;
class Elapsedtime
{
public static void main(String[] args) throws InterruptedException
{
int i,j,t,a;
long startTime = System.nanoTime();
for(i=0;i<1000000000;i++)
{
for(j=0;j<1000000000;j++)
{
a=j;
}
}
long endTime = System.nanoTime();
long timeElapsed = endTime - startTime;
System.out.println("Execution time in nanoseconds : " + timeElapsed + " ns.");
System.out.println("Execution time in milliseconds : " + timeElapsed / 1000000 + " ms.");
startTime = System.nanoTime();
for(t=0;t<1;t++)
{
for(i=0;i<1000000000;i++)
{
for(j=0;j<1000000000;j++)
{
a=j;
}
}
}
endTime = System.nanoTime();
timeElapsed = endTime - startTime;
System.out.println("Execution time in nanoseconds : " + timeElapsed + " ns.");
System.out.println("Execution time in milliseconds : " + timeElapsed / 1000000 + " ms.");
}
}
I am getting the following output.
Execution time in nanoseconds : 17963700 ns. Execution time in milliseconds : 17 ms. Execution time in nanoseconds : 549485500 ns. Execution time in milliseconds : 549 ms.
but I don't expect much difference.