1 /* 2 * Copyright (C) 2016 Google Inc. 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 benchmarks.regression; 18 19 import com.google.caliper.Param; 20 import java.io.File; 21 import java.io.IOException; 22 import java.io.RandomAccessFile; 23 import java.nio.ByteBuffer; 24 import java.nio.ByteOrder; 25 import java.nio.CharBuffer; 26 import java.nio.DoubleBuffer; 27 import java.nio.FloatBuffer; 28 import java.nio.IntBuffer; 29 import java.nio.LongBuffer; 30 import java.nio.ShortBuffer; 31 import java.nio.channels.FileChannel; 32 33 public class ByteBufferBulkBenchmark { 34 @Param({"true", "false"}) private boolean aligned; 35 36 37 enum MyBufferType { 38 DIRECT, HEAP, MAPPED 39 } 40 @Param private MyBufferType srcBufferType; 41 @Param private MyBufferType dataBufferType; 42 43 @Param({"4096", "1232896"}) private int bufferSize; 44 newBuffer(boolean aligned, MyBufferType bufferType, int bsize)45 public static ByteBuffer newBuffer(boolean aligned, MyBufferType bufferType, int bsize) throws IOException { 46 int size = aligned ? bsize : bsize + 8 + 1; 47 ByteBuffer result = null; 48 switch (bufferType) { 49 case DIRECT: 50 result = ByteBuffer.allocateDirect(size); 51 break; 52 case HEAP: 53 result = ByteBuffer.allocate(size); 54 break; 55 case MAPPED: 56 File tmpFile = File.createTempFile("MappedByteBufferTest", ".tmp"); 57 tmpFile.createNewFile(); 58 tmpFile.deleteOnExit(); 59 RandomAccessFile raf = new RandomAccessFile(tmpFile, "rw"); 60 raf.setLength(size); 61 FileChannel fc = raf.getChannel(); 62 result = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size()); 63 break; 64 } 65 result.position(aligned ? 0 : 1); 66 return result; 67 } 68 timeByteBuffer_putByteBuffer(int reps)69 public void timeByteBuffer_putByteBuffer(int reps) throws Exception { 70 ByteBuffer src = ByteBufferBulkBenchmark.newBuffer(aligned, srcBufferType, bufferSize); 71 ByteBuffer data = ByteBufferBulkBenchmark.newBuffer(aligned, dataBufferType, bufferSize); 72 for (int rep = 0; rep < reps; ++rep) { 73 src.position(aligned ? 0 : 1); 74 data.position(aligned ? 0 : 1 ); 75 src.put(data); 76 } 77 } 78 79 } 80