Home | History | Annotate | Download | only in examples
      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 examples;
     18 
     19 import com.google.caliper.BeforeExperiment;
     20 import com.google.caliper.Benchmark;
     21 import com.google.caliper.Param;
     22 
     23 import java.util.AbstractList;
     24 import java.util.List;
     25 
     26 /**
     27  * Measures iterating through list elements.
     28  */
     29 public class ListIterationBenchmark {
     30 
     31   @Param({"0", "10", "100", "1000"})
     32   private int length;
     33 
     34   private List<Object> list;
     35   private Object[] array;
     36 
     37   @BeforeExperiment void setUp() {
     38     array = new Object[length];
     39     for (int i = 0; i < length; i++) {
     40       array[i] = new Object();
     41     }
     42 
     43     list = new AbstractList<Object>() {
     44       @Override public int size() {
     45         return length;
     46       }
     47 
     48       @Override public Object get(int i) {
     49         return array[i];
     50       }
     51     };
     52   }
     53 
     54   @Benchmark int listIteration(int reps) {
     55     int dummy = 0;
     56     for (int i = 0; i < reps; i++) {
     57       for (Object value : list) {
     58         dummy |= value.hashCode();
     59       }
     60     }
     61     return dummy;
     62   }
     63 
     64   @Benchmark int arrayIteration(int reps) {
     65     int dummy = 0;
     66     for (int i = 0; i < reps; i++) {
     67       for (Object value : array) {
     68         dummy |= value.hashCode();
     69       }
     70     }
     71     return dummy;
     72   }
     73 }