1 /* 2 * Copyright (C) 2010 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.common.base.Preconditions; 23 24 import java.util.Random; 25 26 /** 27 * Tests the speed of iteration of different iteration methods for collections. 28 * 29 * @author David Richter 30 */ 31 public class MultisetIteratorBenchmark { 32 @Param({"0", "1", "16", "256", "4096", "65536"}) int size; 33 34 LinkedHashMultiset<Object> linkedHashMultiset; 35 HashMultiset<Object> hashMultiset; 36 37 // TreeMultiset requires a Comparable element. 38 TreeMultiset<Integer> treeMultiset; 39 setUp()40 @BeforeExperiment void setUp() { 41 hashMultiset = HashMultiset.create(size); 42 linkedHashMultiset = LinkedHashMultiset.create(size); 43 treeMultiset = TreeMultiset.create(); 44 45 Random random = new Random(); 46 47 int sizeRemaining = size; 48 49 // TODO(kevinb): generate better test contents for multisets 50 for (int i = 0; sizeRemaining > 0; i++) { 51 // The JVM will return interned values for small ints. 52 Integer value = random.nextInt(1000) + 128; 53 int count = Math.min(random.nextInt(10) + 1, sizeRemaining); 54 sizeRemaining -= count; 55 hashMultiset.add(value, count); 56 linkedHashMultiset.add(value, count); 57 treeMultiset.add(value, count); 58 } 59 60 //TODO(kevinb): convert to assert once benchmark tests enable asserts by default 61 Preconditions.checkState(hashMultiset.size() == size); 62 } 63 hashMultiset(int reps)64 @Benchmark int hashMultiset(int reps) { 65 int sum = 0; 66 for (int i = 0; i < reps; i++) { 67 for (Object value : hashMultiset) { 68 sum += value.hashCode(); 69 } 70 } 71 return sum; 72 } 73 linkedHashMultiset(int reps)74 @Benchmark int linkedHashMultiset(int reps) { 75 int sum = 0; 76 for (int i = 0; i < reps; i++) { 77 for (Object value : linkedHashMultiset) { 78 sum += value.hashCode(); 79 } 80 } 81 return sum; 82 } 83 treeMultiset(int reps)84 @Benchmark int treeMultiset(int reps) { 85 int sum = 0; 86 for (int i = 0; i < reps; i++) { 87 for (Object value : treeMultiset) { 88 sum += value.hashCode(); 89 } 90 } 91 return sum; 92 } 93 } 94