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({
60 "64",
61 "1024",
62 "10240",
63 "102400",
64 "1024000"
65 })
66 public int size;
67
68 @Param
69 public ByteBufType bufferType;
70
71 private ByteBuf targetBuffer;
72
73 private ByteBuf[] sourceBufs;
74
75 @Setup
76 public void setup() {
77 targetBuffer = PooledByteBufAllocator.DEFAULT.directBuffer(size + 2048);
78 sourceBufs = bufferType.sourceBuffers(size);
79 }
80
81 @TearDown
82 public void teardown() {
83 targetBuffer.release();
84 }
85
86 @Benchmark
87 public int writeCBB() {
88 ByteBuf cbb = Unpooled.wrappedBuffer(Integer.MAX_VALUE, sourceBufs);
89 return targetBuffer.clear().writeBytes(cbb).readableBytes();
90 }
91
92 @Benchmark
93 public int writeFCBB() {
94 ByteBuf cbb = Unpooled.wrappedUnmodifiableBuffer(sourceBufs);
95 return targetBuffer.clear().writeBytes(cbb).readableBytes();
96 }
97
98 private static ByteBuf[] makeSmallChunks(int length) {
99
100 List<ByteBuf> buffers = new ArrayList<ByteBuf>(((length + 1) / 48) * 9);
101 for (int i = 0; i < length + 48; i += 48) {
102 for (int j = 4; j <= 12; j++) {
103 buffers.add(wrappedBuffer(new byte[j]));
104 }
105 }
106
107 return buffers.toArray(new ByteBuf[0]);
108 }
109
110 private static ByteBuf[] makeLargeChunks(int length) {
111
112 List<ByteBuf> buffers = new ArrayList<ByteBuf>((length + 1) / 768);
113 for (int i = 0; i < length + 1536; i += 1536) {
114 buffers.add(wrappedBuffer(new byte[512]));
115 buffers.add(wrappedBuffer(new byte[1024]));
116 }
117
118 return buffers.toArray(new ByteBuf[0]);
119 }
120 }