gizgok
gizgok

Reputation: 7639

Why is this Java code not printing Long values?

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.

Upvotes: 0

Views: 1533

Answers (5)

Karl Knechtel
Karl Knechtel

Reputation: 61508

To add to the other answers, depending on your system, System.currentTimeMillis() doesn't necessarily actually count to the nearest millisecond.

Upvotes: 0

vikas27
vikas27

Reputation: 573

Actually both the time is same that is why it is returning 0.

Use this on the top of stop method and it will give u correct answer:

         try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Upvotes: 0

sikrip
sikrip

Reputation: 681

The code

for( int i=0;i<=10;i++) {  
   sum=sum+i;    
}

executes in less than a milisecond :)

Use something like

for( int i=0;i<=10;i++) {  
   sum=sum+i;    
   Thread.sleep(100L);
}

to see a result, although I am not sure what is your goal.

Upvotes: 0

Nico
Nico

Reputation: 1328

Maybe things are running too fast for the clock that currentTimeMillis is using ? This function returns values in milliseconds, but I don't think that it is required that it has a resolution of milliseconds.

In fact: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/System.html#currentTimeMillis()

Upvotes: 1

Prince John Wesley
Prince John Wesley

Reputation: 63688

for( int i=0;i<=10;i++) {  sum=sum+i;    } 

The execution time of the above code is less than a millisecond. Try with System.nanoTime()

Upvotes: 4

Related Questions