1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.buffer;
17
18 import org.openjdk.jmh.annotations.Benchmark;
19 import org.openjdk.jmh.annotations.Measurement;
20 import org.openjdk.jmh.annotations.Param;
21 import org.openjdk.jmh.annotations.Setup;
22 import org.openjdk.jmh.annotations.TearDown;
23 import org.openjdk.jmh.annotations.Warmup;
24
25 import io.netty.microbench.util.AbstractMicrobenchmark;
26
27 import static io.netty.buffer.Unpooled.wrappedBuffer;
28
29 import java.util.ArrayList;
30 import java.util.List;
31 import java.util.concurrent.TimeUnit;
32
33 @Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
34 @Measurement(iterations = 12, time = 1, timeUnit = TimeUnit.SECONDS)
35 public class CompositeByteBufWriteOutBenchmark extends AbstractMicrobenchmark {
36
37 public enum ByteBufType {
38 SMALL_CHUNKS {
39 @Override
40 ByteBuf[] sourceBuffers(int length) {
41 return makeSmallChunks(length);
42 }
43 },
44 LARGE_CHUNKS {
45 @Override
46 ByteBuf[] sourceBuffers(int length) {
47 return makeLargeChunks(length);
48 }
49 };
50 abstract ByteBuf[] sourceBuffers(int length);
51 }
52
53 @Override
54 protected String[] jvmArgs() {
55
56 return new String[] { "-XX:MaxDirectMemorySize=2g", "-Xmx4g", "-Xms4g", "-Xmn3g" };
57 }
58
59 @Param({ "64", "1024", "10240", "102400", "1024000" })
60 public int size;
61
62 @Param
63 public ByteBufType bufferType;
64
65 private ByteBuf targetBuffer;
66
67 private ByteBuf[] sourceBufs;
68
69 @Setup
70 public void setup() {
71 targetBuffer = PooledByteBufAllocator.DEFAULT.directBuffer(size + 2048);
72 sourceBufs = bufferType.sourceBuffers(size);
73 }
74
75 @TearDown
76 public void teardown() {
77 targetBuffer.release();
78 }
79
80 @Benchmark
81 public int writeCBB() {
82 ByteBuf cbb = Unpooled.wrappedBuffer(Integer.MAX_VALUE, sourceBufs);
83 return targetBuffer.clear().writeBytes(cbb).readableBytes();
84 }
85
86 @Benchmark
87 public int writeFCBB() {
88 ByteBuf cbb = Unpooled.wrappedUnmodifiableBuffer(sourceBufs);
89 return targetBuffer.clear().writeBytes(cbb).readableBytes();
90 }
91
92 private static ByteBuf[] makeSmallChunks(int length) {
93
94 List<ByteBuf> buffers = new ArrayList<ByteBuf>(((length + 1) / 48) * 9);
95 for (int i = 0; i < length + 48; i += 48) {
96 for (int j = 4; j <= 12; j++) {
97 buffers.add(wrappedBuffer(new byte[j]));
98 }
99 }
100
101 return buffers.toArray(new ByteBuf[0]);
102 }
103
104 private static ByteBuf[] makeLargeChunks(int length) {
105
106 List<ByteBuf> buffers = new ArrayList<ByteBuf>((length + 1) / 768);
107 for (int i = 0; i < length + 1536; i += 1536) {
108 buffers.add(wrappedBuffer(new byte[512]));
109 buffers.add(wrappedBuffer(new byte[1024]));
110 }
111
112 return buffers.toArray(new ByteBuf[0]);
113 }
114 }