Java Reference
In-Depth Information
33
Arrays.parallelSort(array2);
Instant parallelSortEnd = Instant.now();
34
35
36
// display timing results
37
long parallelSortTime =
38
Duration.between(parallelSortStart, parallelSortEnd).toMillis()
;
39
System.out.printf( "Total time in milliseconds: %d%n%n" ,
40
parallelSortTime);
41
42
// display time difference as a percentage
43
String percentage = NumberFormat.getPercentInstance().format(
( double ) sortTime / parallelSortTime);
44
45
System.out.printf( "%nsort took %s more time than parallelSort%n" ,
46
percentage);
47
}
48
} // end class SortComparison
Starting sort
Total time in milliseconds: 1319
Starting parallelSort
Total time in milliseconds: 323
sort took 408% more time than parallelSort
Fig. 23.28 | Comparing performance of Arrays methods sort and parallelSort . (Part 2 of 2.)
Creating the Arrays
Line 16 uses SecureRandom method ints to create an IntStream of 15,000,000 random
int values, then calls IntStream method toArray to place the values into an array. Lines
17 and 18 copy the array so that the calls to both sort and parallelSort work with the
same set of values.
Timing Arrays Method sort with Date/Time API Classes Instant and Duration
Lines 22 and 24 each call class Instant 's static method now to get the current time before
and after the call to sort . To determine the difference between two Instant s, line 27 uses
class Duration 's static method between , which returns a Duration object containing the
time difference. Next, we call Duration method toMillis to get the difference in milli-
seconds.
Timing Arrays Method parallelSort with Date/Time API Classes Instant and
Duration
Lines 32-34 time the call to Arrays method parallelSort . Then, lines 37-38 calculate
the difference between the Instant s.
Displaying the Percentage Difference Between the Sorting Times
Lines 43-44 use a NumberFormat (package java.text ) to format the ratio of the sort times
as a percentage. NumberFormat static method getPercentInstance returns a Number-
Format that's used to format a number as a percentage. NumberFormat method format per-
forms the formatting. As you can see in the sample output, the sort method took over
400% more time to sort the 15,000,000 random int values.
 
Search WWH ::




Custom Search