blob: 53bcdf8e8e99748052c068d763a8d95c35fdfeb9 [file] [log] [blame]
Jesse Wilson1440b362009-12-15 18:54:02 -08001/*
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 com.google.caliper.examples;
18
19import com.google.caliper.Param;
20import com.google.caliper.Runner;
21import com.google.caliper.SimpleBenchmark;
22
23import java.util.AbstractList;
24import java.util.Arrays;
25import java.util.Collection;
26import java.util.List;
27
28/**
29 * Measures iterating through list elements.
30 */
31public class ListIterationBenchmark extends SimpleBenchmark {
32 @Param private int length;
33
34 private static final Collection<Integer> lengthValues = Arrays.asList(0, 10, 100, 1000);
35
36 private List<Object> list;
37 private Object[] array;
38
39 @Override protected void setUp() {
40 array = new Object[length];
41 for (int i = 0; i < length; i++) {
42 array[i] = new Object();
43 }
44
45 list = new AbstractList<Object>() {
46 @Override public int size() {
47 return length;
48 }
49
50 @Override public Object get(int i) {
51 return array[i];
52 }
53 };
54 }
55
56 public int timeListIteration(int reps) {
57 int count = 0;
58 for (int i = 0; i < reps; i++) {
59 for (Object value : list) {
60 count ^= value.hashCode(); // prevent overoptimization
61 }
62 }
63 return count; // ignored
64 }
65
66 public int timeArrayIteration(int reps) {
67 int count = 0;
68 for (int i = 0; i < reps; i++) {
69 for (Object value : array) {
70 count ^= value.hashCode(); // prevent overoptimization
71 }
72 }
73 return count; // ignored
74 }
75
76 // TODO: remove this from all examples when IDE plugins are ready
77 public static void main(String[] args) throws Exception {
78 Runner.main(ListIterationBenchmark.class, args);
79 }
80}