1 /* 2 * Copyright (C) 2015 The Guava Authors 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.common.collect; 18 19 import com.google.caliper.BeforeExperiment; 20 import com.google.caliper.Benchmark; 21 import com.google.caliper.Param; 22 import com.google.caliper.api.SkipThisScenarioException; 23 import java.util.Random; 24 25 /** A benchmark that tries invoking {@code Set.contains} on many different sets. */ 26 public class MultipleSetContainsBenchmark { 27 28 @Param({"0.0", "0.1", "0.7", "1.0"}) 29 double emptySetProportion; 30 31 @Param({"0.0", "0.1", "0.7", "1.0"}) 32 double singletonSetProportion; 33 34 @Param({"0.2", "0.8"}) 35 double hitRate; 36 37 static final Object PRESENT = new Object(); 38 static final Object ABSENT = new Object(); 39 40 private final ImmutableSet<?>[] sets = new ImmutableSet<?>[0x1000]; 41 42 private final Object[] queries = new Object[0x1000]; 43 44 @BeforeExperiment setUp()45 void setUp() { 46 if (emptySetProportion + singletonSetProportion > 1.01) { 47 throw new SkipThisScenarioException(); 48 } 49 50 Random rng = new Random(); 51 for (int i = 0; i < 0x1000; i++) { 52 double setSize = rng.nextDouble(); 53 if (setSize < emptySetProportion) { 54 sets[i] = ImmutableSet.of(); 55 } else if (setSize < emptySetProportion + singletonSetProportion) { 56 sets[i] = ImmutableSet.of(PRESENT); 57 } else { 58 sets[i] = ImmutableSet.of(PRESENT, new Object()); 59 } 60 61 if (rng.nextDouble() < hitRate) { 62 queries[i] = PRESENT; 63 } else { 64 queries[i] = ABSENT; 65 } 66 } 67 } 68 69 @Benchmark contains(int reps)70 public boolean contains(int reps) { 71 ImmutableSet<?>[] sets = this.sets; 72 Object[] queries = this.queries; 73 boolean result = false; 74 for (int i = 0; i < reps; i++) { 75 int j = i & 0xFFF; 76 result ^= sets[j].contains(queries[j]); 77 } 78 return result; 79 } 80 } 81