Path: blob/master/test/jdk/java/util/Arrays/SortingLongBenchmarkTestJMH.java
41149 views
/*1* Copyright 2015 Goldman Sachs.2* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.3* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.4*5* This code is free software; you can redistribute it and/or modify it6* under the terms of the GNU General Public License version 2 only, as7* published by the Free Software Foundation.8*9* This code is distributed in the hope that it will be useful, but WITHOUT10* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or11* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License12* version 2 for more details (a copy is included in the LICENSE file that13* accompanied this code).14*15* You should have received a copy of the GNU General Public License version16* 2 along with this work; if not, write to the Free Software Foundation,17* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.18*19* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA20* or visit www.oracle.com if you need additional information or have any21* questions.22*/2324import org.openjdk.jmh.annotations.Benchmark;25import org.openjdk.jmh.annotations.BenchmarkMode;26import org.openjdk.jmh.annotations.Measurement;27import org.openjdk.jmh.annotations.Mode;28import org.openjdk.jmh.annotations.OutputTimeUnit;29import org.openjdk.jmh.annotations.Param;30import org.openjdk.jmh.annotations.Scope;31import org.openjdk.jmh.annotations.Setup;32import org.openjdk.jmh.annotations.State;33import org.openjdk.jmh.annotations.Warmup;3435import java.util.ArrayList;36import java.util.Arrays;37import java.util.HashSet;38import java.util.List;39import java.util.Random;40import java.util.Set;41import java.util.concurrent.TimeUnit;4243@State(Scope.Thread)44@BenchmarkMode(Mode.Throughput)45@OutputTimeUnit(TimeUnit.SECONDS)46public class SortingLongBenchmarkTestJMH {47private static final int QUICKSORT_THRESHOLD = 286;48private static final int MAX_RUN_COUNT = 67;49private static final int INSERTION_SORT_THRESHOLD = 47;50public static final int MAX_VALUE = 1_000_000;5152@Param({"pairFlipZeroPairFlip", "descendingAscending", "zeroHi", "hiZeroLow", "hiFlatLow", "identical",53"randomDups", "randomNoDups", "sortedReversedSorted", "pairFlip", "endLessThan"})54public String listType;5556private long[] array;57private static final int LIST_SIZE = 10_000_000;58public static final int NUMBER_OF_ITERATIONS = 10;5960@Setup61public void setUp() {62Random random = new Random(123456789012345L);63this.array = new long[LIST_SIZE];64int threeQuarters = (int) (LIST_SIZE * 0.75);65if ("zeroHi".equals(this.listType)) {66for (int i = 0; i < threeQuarters; i++) {67this.array[i] = 0;68}69int k = 1;70for (int i = threeQuarters; i < LIST_SIZE; i++) {71this.array[i] = k;72k++;73}74}75else if ("hiFlatLow".equals(this.listType)) {76int oneThird = LIST_SIZE / 3;77for (int i = 0; i < oneThird; i++) {78this.array[i] = i;79}80int twoThirds = oneThird * 2;81int constant = oneThird - 1;82for (int i = oneThird; i < twoThirds; i++) {83this.array[i] = constant;84}85for (int i = twoThirds; i < LIST_SIZE; i++) {86this.array[i] = constant - i + twoThirds;87}88}89else if ("hiZeroLow".equals(this.listType)) {90int oneThird = LIST_SIZE / 3;91for (int i = 0; i < oneThird; i++) {92this.array[i] = i;93}94int twoThirds = oneThird * 2;95for (int i = oneThird; i < twoThirds; i++) {96this.array[i] = 0;97}98for (int i = twoThirds; i < LIST_SIZE; i++) {99this.array[i] = oneThird - i + twoThirds;100}101}102else if ("identical".equals(this.listType)) {103for (int i = 0; i < LIST_SIZE; i++) {104this.array[i] = 0;105}106}107else if ("randomDups".equals(this.listType)) {108for (int i = 0; i < LIST_SIZE; i++) {109this.array[i] = random.nextInt(1000);110}111}112else if ("randomNoDups".equals(this.listType)) {113Set<Integer> set = new HashSet<>();114while (set.size() < LIST_SIZE + 1) {115set.add(random.nextInt());116}117List<Integer> list = new ArrayList<>(LIST_SIZE);118list.addAll(set);119for (int i = 0; i < LIST_SIZE; i++) {120this.array[i] = list.get(i);121}122}123else if ("sortedReversedSorted".equals(this.listType)) {124for (int i = 0; i < LIST_SIZE / 2; i++) {125this.array[i] = i;126}127int num = 0;128for (int i = LIST_SIZE / 2; i < LIST_SIZE; i++) {129this.array[i] = LIST_SIZE - num;130num++;131}132}133else if ("pairFlip".equals(this.listType)) {134for (int i = 0; i < LIST_SIZE; i++) {135this.array[i] = i;136}137for (int i = 0; i < LIST_SIZE; i += 2) {138long temp = this.array[i];139this.array[i] = this.array[i + 1];140this.array[i + 1] = temp;141}142}143else if ("endLessThan".equals(this.listType)) {144for (int i = 0; i < LIST_SIZE - 1; i++) {145this.array[i] = 3;146}147this.array[LIST_SIZE - 1] = 1;148}149else if ("pairFlipZeroPairFlip".equals(this.listType)) {150//pairflip151for (int i = 0; i < 64; i++) {152this.array[i] = i;153}154for (int i = 0; i < 64; i += 2) {155long temp = this.array[i];156this.array[i] = this.array[i + 1];157this.array[i + 1] = temp;158}159//zero160for (int i = 64; i < this.array.length - 64; i++) {161this.array[i] = 0;162}163//pairflip164for (int i = this.array.length - 64; i < this.array.length; i++) {165this.array[i] = i;166}167for (int i = this.array.length - 64; i < this.array.length; i += 2) {168long temp = this.array[i];169this.array[i] = this.array[i + 1];170this.array[i + 1] = temp;171}172}173else if ("pairFlipOneHundredPairFlip".equals(this.listType)) {174//10, 5175for (int i = 0; i < 64; i++) {176if (i % 2 == 0) {177this.array[i] = 10;178}179else {180this.array[i] = 5;181}182}183184//100185for (int i = 64; i < this.array.length - 64; i++) {186this.array[i] = 100;187}188189//10, 5190for (int i = this.array.length - 64; i < this.array.length; i++) {191if (i % 2 == 0) {192this.array[i] = 10;193}194else {195this.array[i] = 5;196}197}198}199}200201@Warmup(iterations = 20)202@Measurement(iterations = 10)203@Benchmark204public void sortNewWay() {205for (int i = 0; i < NUMBER_OF_ITERATIONS; i++) {206SortingLongTestJMH.sort(this.array, 0, this.array.length - 1, null, 0, 0);207}208}209210@Warmup(iterations = 20)211@Measurement(iterations = 10)212@Benchmark213public void sortOldWay() {214for (int i = 0; i < NUMBER_OF_ITERATIONS; i++) {215Arrays.sort(this.array);216}217}218219/**220* Sorts the specified range of the array using the given221* workspace array slice if possible for merging222*223* @param a the array to be sorted224* @param left the index of the first element, inclusive, to be sorted225* @param right the index of the last element, inclusive, to be sorted226* @param work a workspace array (slice)227* @param workBase origin of usable space in work array228* @param workLen usable size of work array229*/230static void sort(long[] a, int left, int right,231long[] work, int workBase, int workLen) {232// Use Quicksort on small arrays233if (right - left < QUICKSORT_THRESHOLD) {234SortingLongTestJMH.sort(a, left, right, true);235return;236}237238/*239* Index run[i] is the start of i-th run240* (ascending or descending sequence).241*/242int[] run = new int[MAX_RUN_COUNT + 1];243int count = 0;244run[0] = left;245246// Check if the array is nearly sorted247for (int k = left; k < right; run[count] = k) {248while (k < right && a[k] == a[k + 1])249k++;250if (k == right) break;251if (a[k] < a[k + 1]) { // ascending252while (++k <= right && a[k - 1] <= a[k]) ;253}254else if (a[k] > a[k + 1]) { // descending255while (++k <= right && a[k - 1] >= a[k]) ;256for (int lo = run[count] - 1, hi = k; ++lo < --hi; ) {257long t = a[lo];258a[lo] = a[hi];259a[hi] = t;260}261}262if (run[count] > left && a[run[count]] >= a[run[count] - 1]) {263count--;264}265/*266* The array is not highly structured,267* use Quicksort instead of merge sort.268*/269if (++count == MAX_RUN_COUNT) {270sort(a, left, right, true);271return;272}273}274275// Check special cases276// Implementation note: variable "right" is increased by 1.277if (run[count] == right++) {278run[++count] = right;279}280if (count <= 1) { // The array is already sorted281return;282}283284// Determine alternation base for merge285byte odd = 0;286for (int n = 1; (n <<= 1) < count; odd ^= 1) {287}288289// Use or create temporary array b for merging290long[] b; // temp array; alternates with a291int ao, bo; // array offsets from 'left'292int blen = right - left; // space needed for b293if (work == null || workLen < blen || workBase + blen > work.length) {294work = new long[blen];295workBase = 0;296}297if (odd == 0) {298System.arraycopy(a, left, work, workBase, blen);299b = a;300bo = 0;301a = work;302ao = workBase - left;303}304else {305b = work;306ao = 0;307bo = workBase - left;308}309310// Merging311for (int last; count > 1; count = last) {312for (int k = (last = 0) + 2; k <= count; k += 2) {313int hi = run[k], mi = run[k - 1];314for (int i = run[k - 2], p = i, q = mi; i < hi; ++i) {315if (q >= hi || p < mi && a[p + ao] <= a[q + ao]) {316b[i + bo] = a[p++ + ao];317}318else {319b[i + bo] = a[q++ + ao];320}321}322run[++last] = hi;323}324if ((count & 1) != 0) {325for (int i = right, lo = run[count - 1]; --i >= lo;326b[i + bo] = a[i + ao]327) {328}329run[++last] = right;330}331long[] t = a;332a = b;333b = t;334int o = ao;335ao = bo;336bo = o;337}338}339340/**341* Sorts the specified range of the array by Dual-Pivot Quicksort.342*343* @param a the array to be sorted344* @param left the index of the first element, inclusive, to be sorted345* @param right the index of the last element, inclusive, to be sorted346* @param leftmost indicates if this part is the leftmost in the range347*/348private static void sort(long[] a, int left, int right, boolean leftmost) {349int length = right - left + 1;350351// Use insertion sort on tiny arrays352if (length < INSERTION_SORT_THRESHOLD) {353if (leftmost) {354/*355* Traditional (without sentinel) insertion sort,356* optimized for server VM, is used in case of357* the leftmost part.358*/359for (int i = left, j = i; i < right; j = ++i) {360long ai = a[i + 1];361while (ai < a[j]) {362a[j + 1] = a[j];363if (j-- == left) {364break;365}366}367a[j + 1] = ai;368}369}370else {371/*372* Skip the longest ascending sequence.373*/374do {375if (left >= right) {376return;377}378}379while (a[++left] >= a[left - 1]);380381/*382* Every element from adjoining part plays the role383* of sentinel, therefore this allows us to avoid the384* left range check on each iteration. Moreover, we use385* the more optimized algorithm, so called pair insertion386* sort, which is faster (in the context of Quicksort)387* than traditional implementation of insertion sort.388*/389for (int k = left; ++left <= right; k = ++left) {390long a1 = a[k], a2 = a[left];391392if (a1 < a2) {393a2 = a1;394a1 = a[left];395}396while (a1 < a[--k]) {397a[k + 2] = a[k];398}399a[++k + 1] = a1;400401while (a2 < a[--k]) {402a[k + 1] = a[k];403}404a[k + 1] = a2;405}406long last = a[right];407408while (last < a[--right]) {409a[right + 1] = a[right];410}411a[right + 1] = last;412}413return;414}415416// Inexpensive approximation of length / 7417int seventh = (length >> 3) + (length >> 6) + 1;418419/*420* Sort five evenly spaced elements around (and including) the421* center element in the range. These elements will be used for422* pivot selection as described below. The choice for spacing423* these elements was empirically determined to work well on424* a wide variety of inputs.425*/426int e3 = (left + right) >>> 1; // The midpoint427int e2 = e3 - seventh;428int e1 = e2 - seventh;429int e4 = e3 + seventh;430int e5 = e4 + seventh;431432// Sort these elements using insertion sort433if (a[e2] < a[e1]) {434long t = a[e2];435a[e2] = a[e1];436a[e1] = t;437}438439if (a[e3] < a[e2]) {440long t = a[e3];441a[e3] = a[e2];442a[e2] = t;443if (t < a[e1]) {444a[e2] = a[e1];445a[e1] = t;446}447}448if (a[e4] < a[e3]) {449long t = a[e4];450a[e4] = a[e3];451a[e3] = t;452if (t < a[e2]) {453a[e3] = a[e2];454a[e2] = t;455if (t < a[e1]) {456a[e2] = a[e1];457a[e1] = t;458}459}460}461if (a[e5] < a[e4]) {462long t = a[e5];463a[e5] = a[e4];464a[e4] = t;465if (t < a[e3]) {466a[e4] = a[e3];467a[e3] = t;468if (t < a[e2]) {469a[e3] = a[e2];470a[e2] = t;471if (t < a[e1]) {472a[e2] = a[e1];473a[e1] = t;474}475}476}477}478479// Pointers480int less = left; // The index of the first element of center part481int great = right; // The index before the first element of right part482483if (a[e1] != a[e2] && a[e2] != a[e3] && a[e3] != a[e4] && a[e4] != a[e5]) {484/*485* Use the second and fourth of the five sorted elements as pivots.486* These values are inexpensive approximations of the first and487* second terciles of the array. Note that pivot1 <= pivot2.488*/489long pivot1 = a[e2];490long pivot2 = a[e4];491492/*493* The first and the last elements to be sorted are moved to the494* locations formerly occupied by the pivots. When partitioning495* is complete, the pivots are swapped back into their final496* positions, and excluded from subsequent sorting.497*/498a[e2] = a[left];499a[e4] = a[right];500501/*502* Skip elements, which are less or greater than pivot values.503*/504while (a[++less] < pivot1) {505}506while (a[--great] > pivot2) {507}508509/*510* Partitioning:511*512* left part center part right part513* +--------------------------------------------------------------+514* | < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 |515* +--------------------------------------------------------------+516* ^ ^ ^517* | | |518* less k great519*520* Invariants:521*522* all in (left, less) < pivot1523* pivot1 <= all in [less, k) <= pivot2524* all in (great, right) > pivot2525*526* Pointer k is the first index of ?-part.527*/528outer:529for (int k = less - 1; ++k <= great; ) {530long ak = a[k];531if (ak < pivot1) { // Move a[k] to left part532a[k] = a[less];533/*534* Here and below we use "a[i] = b; i++;" instead535* of "a[i++] = b;" due to performance issue.536*/537a[less] = ak;538++less;539}540else if (ak > pivot2) { // Move a[k] to right part541while (a[great] > pivot2) {542if (great-- == k) {543break outer;544}545}546if (a[great] < pivot1) { // a[great] <= pivot2547a[k] = a[less];548a[less] = a[great];549++less;550}551else { // pivot1 <= a[great] <= pivot2552a[k] = a[great];553}554/*555* Here and below we use "a[i] = b; i--;" instead556* of "a[i--] = b;" due to performance issue.557*/558a[great] = ak;559--great;560}561}562563// Swap pivots into their final positions564a[left] = a[less - 1];565a[less - 1] = pivot1;566a[right] = a[great + 1];567a[great + 1] = pivot2;568569// Sort left and right parts recursively, excluding known pivots570SortingLongTestJMH.sort(a, left, less - 2, leftmost);571SortingLongTestJMH.sort(a, great + 2, right, false);572573/*574* If center part is too large (comprises > 4/7 of the array),575* swap internal pivot values to ends.576*/577if (less < e1 && e5 < great) {578/*579* Skip elements, which are equal to pivot values.580*/581while (a[less] == pivot1) {582++less;583}584585while (a[great] == pivot2) {586--great;587}588589/*590* Partitioning:591*592* left part center part right part593* +----------------------------------------------------------+594* | == pivot1 | pivot1 < && < pivot2 | ? | == pivot2 |595* +----------------------------------------------------------+596* ^ ^ ^597* | | |598* less k great599*600* Invariants:601*602* all in (*, less) == pivot1603* pivot1 < all in [less, k) < pivot2604* all in (great, *) == pivot2605*606* Pointer k is the first index of ?-part.607*/608outer:609for (int k = less - 1; ++k <= great; ) {610long ak = a[k];611if (ak == pivot1) { // Move a[k] to left part612a[k] = a[less];613a[less] = ak;614++less;615}616else if (ak == pivot2) { // Move a[k] to right part617while (a[great] == pivot2) {618if (great-- == k) {619break outer;620}621}622if (a[great] == pivot1) { // a[great] < pivot2623a[k] = a[less];624/*625* Even though a[great] equals to pivot1, the626* assignment a[less] = pivot1 may be incorrect,627* if a[great] and pivot1 are floating-point zeros628* of different signs. Therefore in float and629* double sorting methods we have to use more630* accurate assignment a[less] = a[great].631*/632a[less] = pivot1;633++less;634}635else { // pivot1 < a[great] < pivot2636a[k] = a[great];637}638a[great] = ak;639--great;640}641}642}643644// Sort center part recursively645SortingLongTestJMH.sort(a, less, great, false);646}647else { // Partitioning with one pivot648/*649* Use the third of the five sorted elements as pivot.650* This value is inexpensive approximation of the median.651*/652long pivot = a[e3];653654/*655* Partitioning degenerates to the traditional 3-way656* (or "Dutch National Flag") schema:657*658* left part center part right part659* +-------------------------------------------------+660* | < pivot | == pivot | ? | > pivot |661* +-------------------------------------------------+662* ^ ^ ^663* | | |664* less k great665*666* Invariants:667*668* all in (left, less) < pivot669* all in [less, k) == pivot670* all in (great, right) > pivot671*672* Pointer k is the first index of ?-part.673*/674for (int k = less; k <= great; ++k) {675if (a[k] == pivot) {676continue;677}678long ak = a[k];679if (ak < pivot) { // Move a[k] to left part680a[k] = a[less];681a[less] = ak;682++less;683}684else { // a[k] > pivot - Move a[k] to right part685while (a[great] > pivot) {686--great;687}688if (a[great] < pivot) { // a[great] <= pivot689a[k] = a[less];690a[less] = a[great];691++less;692}693else { // a[great] == pivot694/*695* Even though a[great] equals to pivot, the696* assignment a[k] = pivot may be incorrect,697* if a[great] and pivot are floating-point698* zeros of different signs. Therefore in float699* and double sorting methods we have to use700* more accurate assignment a[k] = a[great].701*/702a[k] = pivot;703}704a[great] = ak;705--great;706}707}708709/*710* Sort left and right parts recursively.711* All elements from center part are equal712* and, therefore, already sorted.713*/714SortingLongTestJMH.sort(a, left, less - 1, leftmost);715SortingLongTestJMH.sort(a, great + 1, right, false);716}717}718719private static void swap(long[] arr, int i, int j) {720long tmp = arr[i];721arr[i] = arr[j];722arr[j] = tmp;723}724}725726727