• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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   @SuppressWarnings("unchecked")
41   private final ImmutableSet<Object>[] sets = new ImmutableSet[0x1000];
42 
43   private final Object[] queries = new Object[0x1000];
44 
45   @BeforeExperiment
setUp()46   void setUp() {
47     if (emptySetProportion + singletonSetProportion > 1.01) {
48       throw new SkipThisScenarioException();
49     }
50 
51     Random rng = new Random();
52     for (int i = 0; i < 0x1000; i++) {
53       double setSize = rng.nextDouble();
54       if (setSize < emptySetProportion) {
55         sets[i] = ImmutableSet.of();
56       } else if (setSize < emptySetProportion + singletonSetProportion) {
57         sets[i] = ImmutableSet.of(PRESENT);
58       } else {
59         sets[i] = ImmutableSet.of(PRESENT, new Object());
60       }
61 
62       if (rng.nextDouble() < hitRate) {
63         queries[i] = PRESENT;
64       } else {
65         queries[i] = ABSENT;
66       }
67     }
68   }
69 
70   @Benchmark
contains(int reps)71   public boolean contains(int reps) {
72     ImmutableSet<Object>[] sets = this.sets;
73     Object[] queries = this.queries;
74     boolean result = false;
75     for (int i = 0; i < reps; i++) {
76       int j = i & 0xFFF;
77       result ^= sets[j].contains(queries[j]);
78     }
79     return result;
80   }
81 }
82