我正在处理一些SocketChannel
-to-SocketChannel
代码,最好使用直接的字节缓冲区 -- 长时间存活且大(每个连接数十到数百兆字节)。在使用FileChannel
并确定确切的循环结构时,我对ByteBuffer.allocate()
和ByteBuffer.allocateDirect()
的性能进行了微型基准测试。
结果中有一个我无法解释的惊喜。在下面的图表中,对于ByteBuffer.allocate()
传输实现,在256KB和512KB处存在非常明显的悬崖--性能下降了约50%!ByteBuffer.allocateDirect()
也似乎存在较小的性能瓶颈。("增益百分比"系列有助于可视化这些变化。)
缓冲区大小(字节)与时间(毫秒)
ByteBuffer.allocate()
和ByteBuffer.allocateDirect()
之间的奇怪性能曲线差异是什么原因? 究竟发生了什么?
这可能很大程度上取决于硬件和操作系统,因此这里提供这些细节:
- MacBook Pro带双核Core 2 CPU
- Intel X25M SSD驱动器
- OSX 10.6.4
如有需要,可提供源代码。
package ch.dietpizza.bench;
import static java.lang.String.format;
import static java.lang.System.out;
import static java.nio.ByteBuffer.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
public class SocketChannelByteBufferExample {
private static WritableByteChannel target;
private static ReadableByteChannel source;
private static ByteBuffer buffer;
public static void main(String[] args) throws IOException, InterruptedException {
long timeDirect;
long normal;
out.println("start");
for (int i = 512; i <= 1024 * 1024 * 64; i *= 2) {
buffer = allocateDirect(i);
timeDirect = copyShortest();
buffer = allocate(i);
normal = copyShortest();
out.println(format("%d, %d, %d", i, normal, timeDirect));
}
out.println("stop");
}
private static long copyShortest() throws IOException, InterruptedException {
int result = 0;
for (int i = 0; i < 100; i++) {
int single = copyOnce();
result = (i == 0) ? single : Math.min(result, single);
}
return result;
}
private static int copyOnce() throws IOException, InterruptedException {
initialize();
long start = System.currentTimeMillis();
while (source.read(buffer)!= -1) {
buffer.flip();
target.write(buffer);
buffer.clear(); //pos = 0, limit = capacity
}
long time = System.currentTimeMillis() - start;
rest();
return (int)time;
}
private static void initialize() throws UnknownHostException, IOException {
InputStream is = new FileInputStream(new File("/Users/stu/temp/robyn.in"));//315 MB file
OutputStream os = new FileOutputStream(new File("/dev/null"));
target = Channels.newChannel(os);
source = Channels.newChannel(is);
}
private static void rest() throws InterruptedException {
System.gc();
Thread.sleep(200);
}
}