liyujie
2025-08-29 87c7c0d90966d729ca3d39cbfca77a39a43960eb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
 * Copyright (C) 2016 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package benchmarks.regression;
 
import com.google.caliper.Param;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.nio.channels.FileChannel;
 
public class ByteBufferBulkBenchmark {
    @Param({"true", "false"}) private boolean aligned;
 
 
    enum MyBufferType {
        DIRECT, HEAP, MAPPED
    }
    @Param private MyBufferType srcBufferType;
    @Param private MyBufferType dataBufferType;
 
    @Param({"4096", "1232896"}) private int bufferSize;
 
    public static ByteBuffer newBuffer(boolean aligned, MyBufferType bufferType, int bsize) throws IOException {
        int size = aligned ?  bsize : bsize + 8 + 1;
        ByteBuffer result = null;
        switch (bufferType) {
        case DIRECT:
            result = ByteBuffer.allocateDirect(size);
            break;
        case HEAP:
            result = ByteBuffer.allocate(size);
            break;
        case MAPPED:
            File tmpFile = File.createTempFile("MappedByteBufferTest", ".tmp");
            tmpFile.createNewFile();
            tmpFile.deleteOnExit();
            RandomAccessFile raf = new RandomAccessFile(tmpFile, "rw");
            raf.setLength(size);
            FileChannel fc = raf.getChannel();
            result = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size());
            break;
        }
        result.position(aligned ? 0 : 1);
        return result;
    }
 
    public void timeByteBuffer_putByteBuffer(int reps) throws Exception {
        ByteBuffer src = ByteBufferBulkBenchmark.newBuffer(aligned, srcBufferType, bufferSize);
        ByteBuffer data = ByteBufferBulkBenchmark.newBuffer(aligned, dataBufferType, bufferSize);
        for (int rep = 0; rep < reps; ++rep) {
            src.position(aligned ? 0 : 1);
            data.position(aligned ? 0 : 1 );
            src.put(data);
        }
    }
 
}