2

I've just started learning about various algorithms, and I'm attempting to write a program that tests the speed between the algorithms and outputs the time it takes each of them to run to the screen. As I've set it up, each algorithm is a subclass of a RunnableAlgorithm abstract class that creates new arrays of the same parameters for each iteration of the algorithm.

However, with each iteration of the algorithm, it seems to run faster! This is a snippet of the output - I've tried it several times, and it consistently will get faster the more times I run it.

SelectionSort warmup .. 45695528 ns
SelectionSort: 996415 ns
SelectionSort: 1044200 ns
SelectionSort: 1260648 ns
SelectionSort: 774839 ns
SelectionSort: 738320 ns
SelectionSort: 337446 ns

It has a "warmup" method called in the superclass ctor that (from my understanding) should load all of the used classes.

Warmup calls all the classes that are later called, which includes DecimalFormat, Random, System (for System.nanoTime() and System.out), along with running the algorithm several times.

 SelectionSort s = new SelectionSort();
   for (int i = 0; i < 6; i++) {
     s.setTime();
     s.algorithmAverage();
     s.printTime();
 }

setTime() sets a variable such that:

beginTime = System.nanoTime(); 

and printTime() is:

System.out.println(this.getClass().getName() + ": " + new
    DecimalFormat(DECIMAL).format( System.nanoTime() - beginTime)
    + " ns");

and algorithmAverage() runs the algorithm 10 times, which is what is being timed. Can anyone help me understand why it speeds up? Is the JVM optimizing the code to run because it's called so often? Is there a better, more consistent way for me to test the algorithms speeds other than System.nanoTime() which seems to be fairly unreliable?

Thank you in advanced!

Stefan Falk
  • 23,898
  • 50
  • 191
  • 378
  • 1
    Note that writing benchmarks is *hard*. If you're wanting to compare the speed of algorithms for different inputs, a framework such as JMH or Caliper will likely get you more meaningful numbers. – Andy Turner Dec 08 '17 at 12:30

0 Answers0