1/*
2 * Copyright (C) 2009 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package examples;
18
19import com.google.caliper.BeforeExperiment;
20import com.google.caliper.Benchmark;
21import com.google.caliper.Param;
22
23import java.util.Arrays;
24import java.util.Random;
25
26/**
27 * Measures sorting on different distributions of integers.
28 */
29public class ArraySortBenchmark {
30
31  @Param({"10", "100", "1000", "10000"}) private int length;
32
33  @Param private Distribution distribution;
34
35  private int[] values;
36  private int[] copy;
37
38  @BeforeExperiment void setUp() throws Exception {
39    values = distribution.create(length);
40    copy = new int[length];
41  }
42
43  @Benchmark void sort(int reps) {
44    for (int i = 0; i < reps; i++) {
45      System.arraycopy(values, 0, copy, 0, values.length);
46      Arrays.sort(copy);
47    }
48  }
49
50  public enum Distribution {
51    SAWTOOTH {
52      @Override
53      int[] create(int length) {
54        int[] result = new int[length];
55        for (int i = 0; i < length; i += 5) {
56          result[i] = 0;
57          result[i + 1] = 1;
58          result[i + 2] = 2;
59          result[i + 3] = 3;
60          result[i + 4] = 4;
61        }
62        return result;
63      }
64    },
65    INCREASING {
66      @Override
67      int[] create(int length) {
68        int[] result = new int[length];
69        for (int i = 0; i < length; i++) {
70          result[i] = i;
71        }
72        return result;
73      }
74    },
75    DECREASING {
76      @Override
77      int[] create(int length) {
78        int[] result = new int[length];
79        for (int i = 0; i < length; i++) {
80          result[i] = length - i;
81        }
82        return result;
83      }
84    },
85    RANDOM {
86      @Override
87      int[] create(int length) {
88        Random random = new Random();
89        int[] result = new int[length];
90        for (int i = 0; i < length; i++) {
91          result[i] = random.nextInt();
92        }
93        return result;
94      }
95    };
96
97    abstract int[] create(int length);
98  }
99}
100