long stime=System.currentTimeMillis();
for(int i=0;i<500000;i++)
{
String s1="Hello";
String s2="Hello";
}
long etime=System.currentTimeMillis();
System.out.println("Time diff"+(etime-stime));
long stime1=System.currentTimeMillis();
for(int i=0;i<500000;i++)
{
String s3=new String("Hello");
String s4=new String("Hello");
}
long etime1=System.currentTimeMillis();
System.out.println("Time diff"+(etime1-stime1));
Actually I am getting 0 answer in both case. Why zero is in both case
use System.nanoTime() for execution time.Replace System.currentTimeMillis(); with System.nanoTime();
System.nanoTime() gives you a nanosecond resolution timer which is at least micro-second accurate on most systems. This allows you to see smaller intervals of time which are less than a milli-second.
Why zero is in both case
You code doesn't do anything useful so it not too surprising it is taking 0 milli-seconds. It could take 900,000 nano-seconds or about 3,000,000 clock cycles, but still be in the same milli-second.
Instead of using System.currentTimeMillis() you could use System.nanoTime()
This won't tell you how the code takes to run, but instead it will tell you how long it takes for the JVM to detect the code doesn't do anything useful and optimise it away.
In short, a milli-seconds is an eternity of a computer. A 10 core CPU can perform up to 3 instructions per clock cycle at 3.5 GHz could do 100,000,000 instructions in a milli-second (you would be lucky if it did 1% of that however) The other key thing to remember is that the JVM optimises the code dynamically which means it starts slow and get faster and if you don't do anything useful, you are likely to get equally useful timings ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With