Home | History | Annotate | Download | only in examples
      1 /*
      2  * Copyright (C) 2010 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.ArrayList;
     24 import java.util.Arrays;
     25 import java.util.Collections;
     26 import java.util.HashSet;
     27 import java.util.List;
     28 import java.util.Random;
     29 import java.util.Set;
     30 
     31 public class ContainsBenchmark {
     32   @Param({"0", "25", "50", "75", "100"}) private int percentNulls;
     33   @Param({"100", "1000", "10000"}) private int containsPerRep;
     34 
     35   /** the set under test */
     36   private final Set<String> set = new HashSet<String>();
     37 
     38   /** twenty-five percent nulls */
     39   private final List<Object> queries = new ArrayList<Object>();
     40 
     41   @BeforeExperiment void setUp() {
     42     set.addAll(Arrays.asList("str1", "str2", "str3", "str4"));
     43     int nullThreshold = percentNulls * containsPerRep / 100;
     44     for (int i = 0; i < nullThreshold; i++) {
     45       queries.add(null);
     46     }
     47     for (int i = nullThreshold; i < containsPerRep; i++) {
     48       queries.add(new Object());
     49     }
     50     Collections.shuffle(queries, new Random(0));
     51   }
     52 
     53   @Benchmark void contains(int reps) {
     54     for (int i = 0; i < reps; i++) {
     55       for (Object query : queries) {
     56         set.contains(query);
     57       }
     58     }
     59   }
     60 }
     61