1

For some reason I can get the start time and the stop time in my program (which is normally a difference of 3 milliseconds) but when I print the result of the getElapsedTime() method it always comes back with 0. Above the listed code is the creation of a StopWatch object named sortTime.

Perhaps there is a problem with rounding? Perhaps there is a problem with the getElapsedTime() method itself?

    System.out.println(sortTime.start()); // Start Timer

    java.util.Arrays.sort(numbers); // Sort the array

    System.out.println(sortTime.stop());// stop timer

    System.out.println("the elapsed time is: " + sortTime.getElapsedTime());
    }
} //end of main class (used for testing)

//Define Class
 class StopWatch {
 long startTime;
 long endTime;

 //Constructors
 public StopWatch () { 
 }

 //Methods
long start() {
    long startTime = System.currentTimeMillis();
    return startTime; 
}
long stop() {
    long endTime = System.currentTimeMillis();
    return endTime; 
}
long getElapsedTime() {
        return (endTime - startTime);
    }
     }

For example, when I run the program the result is:

1442877972466
1442877972469
the elapsed time is: 0

A. Crozier
  • 23
  • 1
  • 7

2 Answers2

4

You are creating local variables with the same name as class variables:

long start() {
    long startTime = System.currentTimeMillis();
    return startTime; 
}

The use of long startTime in this function makes a local variable that is different from the class member named startTime. Change this to:

long start() {
    startTime = System.currentTimeMillis();
    return startTime; 
}
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
3

startTime and endTime have been redeclared/shadowed as local variables, leaving the instance fields with their default values (of 0)

long start() {
    long startTime = System.currentTimeMillis();
    return startTime; 
}
long stop() {
    long endTime = System.currentTimeMillis();
    return endTime; 
}

Instead, make use of the instance fields...

long start() {
    startTime = System.currentTimeMillis();
    return startTime; 
}
long stop() {
    endTime = System.currentTimeMillis();
    return endTime; 
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366