I wrote a simple Stopwatch class as follows.
public class StopWatch
{
private long startTime;
private long stopTime;
private boolean isRunning;
public void Start()
{
this.startTime=System.currentTimeMillis();
this.isRunning=true;
}
public void Stop()
{
this.stopTime=System.currentTimeMillis();
this.isRunning=false;
}
public long timeElapsed()
{
if(isRunning)
{
return ((System.currentTimeMillis()-startTime));
}
else
{
return ((stopTime-startTime));
}
}
public static void main(String[] args)
{
StopWatch s=new StopWatch();
try
{
s.Start();
int sum=0;
for( int i=0;i<=10;i++)
{
sum=sum+i;
}
s.Stop();
long timetaken=s.timeElapsed();
System.out.println(timetaken);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
If I add +100L to stop time then I get answer as 100. For some reason both starttime and stoptime have the same value and the subtraction is 0. Not sure why that is happening.
I had also put 100000 as the loop counter and even that had given me 0. While copy pasting code the value was 10 in for loop.
With nanoseconds it’s working fine, I was trying to check for performance issues that come with autoboxing in Java.
The execution time of the above code is
less than a millisecond. Try withSystem.nanoTime()