我正在研究一些使用直接字节SocketChannel
缓冲区SocketChannel
效果最好的代码 - 寿命长且大(每个连接数十到数百兆字节。)在用FileChannel
s 散列确切的循环结构时,我运行了一些微 -ByteBuffer.allocate()
与ByteBuffer.allocateDirect()
性能的基准。
结果令人惊讶,我无法真正解释。在下图中,ByteBuffer.allocate()
传输实现在 256KB 和 512KB 处有一个非常明显的悬崖——性能下降了约 50%!似乎还有一个较小的性能悬崖ByteBuffer.allocateDirect()
。(%-gain 系列有助于可视化这些变化。)
缓冲区大小(字节)与时间 (MS)
ByteBuffer.allocate()
为什么和之间出现奇数的性能曲线差异ByteBuffer.allocateDirect()
? 幕后究竟发生了什么?
它很可能依赖于硬件和操作系统,所以这里有这些细节:
- 配备双核 Core 2 CPU 的 MacBook Pro
- 英特尔 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);
}
}