Java Stream How to - Benchmark the Sort and parallel sort








Question

We would like to know how to benchmark the Sort and parallel sort.

Answer

//from w ww  .j a  v a2s .c o m
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
  public static void main(String[] args) throws FileNotFoundException {
    List<Integer> arraySource = new ArrayList<>();
    for (int i = 0; i < 99999; i++) {
      arraySource.add(i);
    }

    Integer[] myArray = new Integer[999];
    myArray = arraySource.toArray(myArray);
    long startTime = System.currentTimeMillis();
    Arrays.sort(myArray);
    long endTime = System.currentTimeMillis();
    System.out
        .println("Time take in serial: " + (endTime - startTime) / 1000.0);

    Integer[] myArray2 = new Integer[999];
    myArray2 = arraySource.toArray(myArray);
    startTime = System.currentTimeMillis();
    Arrays.parallelSort(myArray2);
    endTime = System.currentTimeMillis();
    System.out.println("Time take in parallel: " + (endTime - startTime)
        / 1000.0);

  }
}

The code above generates the following result.