Java SE 8 parallelSort in Arrays class

Arrays class now has several new “parallel” methods to take advantage of multi-core hardware. Arrays method parallelSort can sort large arrays more efficiently on multicore systems. Lets create a very large array and use Java SE 8 Date/Time API to compare how long it takes to sort the array with methods sort and parallelSort.

 SecureRandom random = new SecureRandom();
 // generate array of random ints, then copy it intArray1
 int[] intArray1 = random.ints(18_000_000).toArray();
 // Create another arrary
 int[] intArray2 = new int[intArray1.length];
 System.arraycopy(intArray1, 0, intArray2, 0, intArray1.length);
 
 System.out.println("Perform Arrays.sort");
 Instant sortStart = Instant.now();
 Arrays.sort(intArray1);              
 Instant sortEnd = Instant.now();  
 
long sortTime = Duration.between(sortStart, sortEnd).toMillis();
 System.out.printf("Total time in milliseconds: %d%n%n", sortTime);
 
 // time the sorting of intArray2 with Arrays method parallelSort
 System.out.println("Perform Arrays.parallelSort");
 Instant parallelSortStart = Instant.now();
 Arrays.parallelSort(intArray2);              
 Instant parallelSortEnd = Instant.now();  
 
 long parallelSortTime =Duration.between(parallelSortStart, parallelSortEnd).toMillis();
 System.out.printf("Total time in milliseconds: %d%n%n",parallelSortTime);
 
 String percentage = NumberFormat.getPercentInstance().format((double) sortTime / parallelSortTime);                    
 System.out.printf("%nArrays.sort took %s more time than Arrays.parallelSort%n", percentage);

Output

Perform Arrays.sort
Total time in milliseconds: 1738

Perform Arrays.parallelSort
Total time in milliseconds: 435


Arrays.sort took 400% more time than Arrays.parallelSort

 

 

Let's Share
Exit mobile version