Jesse Wilson | e95457f | 2009-12-10 15:45:23 -0800 | [diff] [blame^] | 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 | |
| 17 | package com.google.caliper.examples; |
| 18 | |
| 19 | import com.google.caliper.Benchmark; |
| 20 | import com.google.caliper.DefaultBenchmarkSuite; |
| 21 | import com.google.caliper.Param; |
| 22 | import com.google.caliper.Runner; |
| 23 | |
| 24 | import java.util.*; |
| 25 | |
| 26 | /** |
| 27 | * Measures iterating through list elements. |
| 28 | */ |
| 29 | public class ListIterationBenchmarkSuite extends DefaultBenchmarkSuite { |
| 30 | |
| 31 | @Param private int length; |
| 32 | |
| 33 | private static Collection<Integer> lengthValues = Arrays.asList(0, 10, 100, 1000); |
| 34 | |
| 35 | private List<Object> list; |
| 36 | private Object[] array; |
| 37 | |
| 38 | @Override protected void setUp() throws Exception { |
| 39 | array = new Object[length]; |
| 40 | for (int i = 0; i < length; i++) { |
| 41 | array[i] = new Object(); |
| 42 | } |
| 43 | |
| 44 | list = new AbstractList<Object>() { |
| 45 | @Override public int size() { |
| 46 | return length; |
| 47 | } |
| 48 | |
| 49 | @Override public Object get(int i) { |
| 50 | return array[i]; |
| 51 | } |
| 52 | }; |
| 53 | } |
| 54 | |
| 55 | class ListIterateBenchmark extends Benchmark { |
| 56 | @Override public Object run(int trials) throws Exception { |
| 57 | int count = 0; |
| 58 | for (int i = 0; i < trials; i++) { |
| 59 | for (Object value : list) { |
| 60 | count ^= (value == Boolean.TRUE) ? i : 0; |
| 61 | } |
| 62 | } |
| 63 | return count > 0; |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | class ArrayIterateBenchmark extends Benchmark { |
| 68 | @Override public Object run(int trials) throws Exception { |
| 69 | int count = 0; |
| 70 | for (int i = 0; i < trials; i++) { |
| 71 | for (Object value : array) { |
| 72 | count ^= (value == Boolean.TRUE) ? i : 0; |
| 73 | } |
| 74 | } |
| 75 | return count > 0; |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | public static void main(String[] args) { |
| 80 | Runner.main(ListIterationBenchmarkSuite.class, args); |
| 81 | } |
| 82 | } |