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.primitives; 18 19 import com.google.caliper.BeforeExperiment; 20 import com.google.caliper.Benchmark; 21 import com.google.caliper.Param; 22 import java.util.Arrays; 23 import java.util.Comparator; 24 import java.util.Random; 25 26 /** 27 * Microbenchmark for {@link UnsignedBytes}. 28 * 29 * @author Hiroshi Yamauchi 30 */ 31 public class UnsignedBytesBenchmark { 32 33 private byte[] ba1; 34 private byte[] ba2; 35 private byte[] ba3; 36 private byte[] ba4; 37 private Comparator<byte[]> javaImpl; 38 private Comparator<byte[]> unsafeImpl; 39 40 // 4, 8, 64, 1K, 1M, 1M (unaligned), 64M, 64M (unaligned) 41 // @Param({"4", "8", "64", "1024", "1048576", "1048577", "6710884", "6710883"}) 42 @Param({"4", "8", "64", "1024"}) 43 private int length; 44 45 @BeforeExperiment setUp()46 void setUp() throws Exception { 47 Random r = new Random(); 48 ba1 = new byte[length]; 49 r.nextBytes(ba1); 50 ba2 = Arrays.copyOf(ba1, ba1.length); 51 // Differ at the last element 52 ba3 = Arrays.copyOf(ba1, ba1.length); 53 ba4 = Arrays.copyOf(ba1, ba1.length); 54 ba3[ba1.length - 1] = (byte) 43; 55 ba4[ba1.length - 1] = (byte) 42; 56 57 javaImpl = UnsignedBytes.lexicographicalComparatorJavaImpl(); 58 unsafeImpl = UnsignedBytes.LexicographicalComparatorHolder.UnsafeComparator.INSTANCE; 59 } 60 61 @Benchmark longEqualJava(int reps)62 void longEqualJava(int reps) { 63 for (int i = 0; i < reps; ++i) { 64 if (javaImpl.compare(ba1, ba2) != 0) { 65 throw new Error(); // deoptimization 66 } 67 } 68 } 69 70 @Benchmark longEqualUnsafe(int reps)71 void longEqualUnsafe(int reps) { 72 for (int i = 0; i < reps; ++i) { 73 if (unsafeImpl.compare(ba1, ba2) != 0) { 74 throw new Error(); // deoptimization 75 } 76 } 77 } 78 79 @Benchmark diffLastJava(int reps)80 void diffLastJava(int reps) { 81 for (int i = 0; i < reps; ++i) { 82 if (javaImpl.compare(ba3, ba4) == 0) { 83 throw new Error(); // deoptimization 84 } 85 } 86 } 87 88 @Benchmark diffLastUnsafe(int reps)89 void diffLastUnsafe(int reps) { 90 for (int i = 0; i < reps; ++i) { 91 if (unsafeImpl.compare(ba3, ba4) == 0) { 92 throw new Error(); // deoptimization 93 } 94 } 95 } 96 97 /* 98 try { 99 UnsignedBytesBenchmark bench = new UnsignedBytesBenchmark(); 100 bench.length = 1024; 101 bench.setUp(); 102 bench.timeUnsafe(100000); 103 } catch (Exception e) { 104 }*/ 105 } 106