Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be answer of the following in java?

Tags:

java

loops

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

like image 720
Ritesh Avatar asked Jan 27 '26 02:01

Ritesh


2 Answers

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.

like image 188
SpringLearner Avatar answered Jan 29 '26 16:01

SpringLearner


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 ;)

like image 44
Peter Lawrey Avatar answered Jan 29 '26 14:01

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!