1 /* 2 * Copyright (C) 2012 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.hash; 18 19 import com.google.caliper.BeforeExperiment; 20 import com.google.caliper.Benchmark; 21 import com.google.caliper.Param; 22 import java.util.Random; 23 24 /** 25 * Benchmarks for comparing the various {@link HashFunction functions} that we provide. 26 * 27 * <p>Parameters for the benchmark are: 28 * 29 * <ul> 30 * <li>size: The length of the byte array to hash. 31 * <li>hashFunctionEnum: The {@link HashFunction} to use for hashing. 32 * </ul> 33 * 34 * @author Kurt Alfred Kluever 35 */ 36 public class HashFunctionBenchmark { 37 38 // Use a statically configured random instance for all of the benchmarks 39 private static final Random random = new Random(42); 40 41 @Param({"10", "1000", "100000", "1000000"}) 42 private int size; 43 44 @Param HashFunctionEnum hashFunctionEnum; 45 46 private byte[] testBytes; 47 48 @BeforeExperiment setUp()49 void setUp() { 50 testBytes = new byte[size]; 51 random.nextBytes(testBytes); 52 } 53 54 @Benchmark hasher(int reps)55 int hasher(int reps) { 56 HashFunction hashFunction = hashFunctionEnum.getHashFunction(); 57 int result = 37; 58 for (int i = 0; i < reps; i++) { 59 result ^= hashFunction.newHasher().putBytes(testBytes).hash().asBytes()[0]; 60 } 61 return result; 62 } 63 64 @Benchmark hashFunction(int reps)65 int hashFunction(int reps) { 66 HashFunction hashFunction = hashFunctionEnum.getHashFunction(); 67 int result = 37; 68 for (int i = 0; i < reps; i++) { 69 result ^= hashFunction.hashBytes(testBytes).asBytes()[0]; 70 } 71 return result; 72 } 73 74 @Benchmark hashFunctionWithOffset(int reps)75 int hashFunctionWithOffset(int reps) { 76 HashFunction hashFunction = hashFunctionEnum.getHashFunction(); 77 int result = 37; 78 for (int i = 0; i < reps; i++) { 79 result ^= hashFunction.hashBytes(testBytes, 1, testBytes.length - 1).asBytes()[0]; 80 } 81 return result; 82 } 83 } 84