blob: f42390fbc872248a43521b51ba5e8dfbffa7b52c [file] [log] [blame]
Paul Duffin7fc0b452015-11-10 17:45:15 +00001/*
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.Param;
20import com.google.caliper.Runner;
21import com.google.caliper.SimpleBenchmark;
22import java.util.Arrays;
23import java.util.Random;
24
25/**
26 * Measures sorting on different distributions of integers.
27 */
28public class ArraySortBenchmark extends SimpleBenchmark {
29
30 @Param({"10", "100", "1000", "10000"}) private int length;
31
32 @Param private Distribution distribution;
33
34 private int[] values;
35 private int[] copy;
36
37 @Override protected void setUp() throws Exception {
38 values = distribution.create(length);
39 copy = new int[length];
40 }
41
42 public void timeSort(int reps) {
43 for (int i = 0; i < reps; i++) {
44 System.arraycopy(values, 0, copy, 0, values.length);
45 Arrays.sort(copy);
46 }
47 }
48
49 public enum Distribution {
50 SAWTOOTH {
51 @Override
52 int[] create(int length) {
53 int[] result = new int[length];
54 for (int i = 0; i < length; i += 5) {
55 result[i] = 0;
56 result[i + 1] = 1;
57 result[i + 2] = 2;
58 result[i + 3] = 3;
59 result[i + 4] = 4;
60 }
61 return result;
62 }
63 },
64 INCREASING {
65 @Override
66 int[] create(int length) {
67 int[] result = new int[length];
68 for (int i = 0; i < length; i++) {
69 result[i] = i;
70 }
71 return result;
72 }
73 },
74 DECREASING {
75 @Override
76 int[] create(int length) {
77 int[] result = new int[length];
78 for (int i = 0; i < length; i++) {
79 result[i] = length - i;
80 }
81 return result;
82 }
83 },
84 RANDOM {
85 @Override
86 int[] create(int length) {
87 Random random = new Random();
88 int[] result = new int[length];
89 for (int i = 0; i < length; i++) {
90 result[i] = random.nextInt();
91 }
92 return result;
93 }
94 };
95
96 abstract int[] create(int length);
97 }
98
99 public static void main(String[] args) throws Exception {
100 Runner.main(ArraySortBenchmark.class, args);
101 }
102}