I want to test the runtime of some sorting algorithm with the following code
int n = 2000;
for(int i=0; i<10; i++){
n *= 2;
init(array, n); // initializes array with n elements
long startTime = System.nanoTime();
sort(array;
long elapsedTime = System.nanoTime()-startTime;
System.out.println("Size: "+n+"\t\tTime: "+elapsedTime/1000000+"(ms)");
}
The output is
Size: 4000 Time: 0(ms)
Size: 8000 Time: 0(ms)
Size: 16000 Time: 0(ms)
Size: 32000 Time: 0(ms)
Size: 64000 Time: 0(ms)
Size: 128000 Time: 0(ms)
Size: 256000 Time: 0(ms)
Size: 512000 Time: 0(ms)
Size: 1024000 Time: 0(ms)
Size: 2048000 Time: 0(ms)
The problem is not with algorithm, it sorts arrays properly, and it takes noticeable time to do the job for large arrays. This example took about 10 seconds to run. I think I used the nanoTime() just as described in the Java documentation. I searched the answer for this problem and it seems that people have experienced a similar issue. E.g., here Is there a stopwatch in Java?. However, I could not find the answer how to resolve the issue. There were suggestions to use apache's StopWatch, but from what I understood, it uses similar calls to nanoTime(). So, how to fix this problem? If it makes a difference, I am running the code in Windows 7 with jre 1.8.0_31. Thanks