Java I/O与NIO:快速基准比较

7
我最近读到,较新的计算机上,由于多核机器的新可用性,Java的I/O表现比NIO更好。
我在使用本地回环地址的局域网上进行了一项快速测试,比较了I/O和NIO的传输时间。
注:这是使用JDK 7
结果(3次试验):
I/O传输平均需要21789.3毫秒
NIO传输平均需要22771.0毫秒
值得注意的是,与I/O相比,每次NIO传输的CPU使用率似乎高了约10%。
我的问题是,我的比较代码是否公平? 我编写的I/O和NIO代码是否良好/相等? 如果不是,我该如何改进并重新运行此测试?
    public static void main(String[] args) {
    System.out.println("Initiating test sequence...");
    new Thread(new Client()).start();
    try {
        System.out.println("Server I/O initiating...");
        ServerSocket server = new ServerSocket(5555);
        Socket sock = server.accept();
        System.out.println("Server connected to client successfully");
        InputStream is = sock.getInputStream();
        File output = new File("C:/test_root/video.avi");
        FileOutputStream fos = new FileOutputStream(output);
        byte[] data = new byte[1024];
        int len=0;
        System.out.println("Server initiating transfer - Timer starting");
        long start = System.currentTimeMillis();
        while((len=is.read(data))>0) {
            fos.write(data, 0, len);
            fos.flush();
        }
        fos.close();
        is.close();
        sock.close();
        server.close();
        long end = System.currentTimeMillis();
        System.out.println("Network I/O transfer time = "+(end-start)+"ms");

        System.out.println("Server NIO initiating...");
        ServerSocketChannel serverChan = ServerSocketChannel.open();
        serverChan.bind(new InetSocketAddress(5555));
        SocketChannel chan = serverChan.accept();
        chan.configureBlocking(false);
        System.out.println("Server channel connected");
        FileChannel fc = (FileChannel) Files.newByteChannel(Paths.get("C:/test_root/video.avi"), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        ByteBuffer buff = ByteBuffer.allocate(1024);
        System.out.println("Server initiating transfer - Timer starting");
        start = System.currentTimeMillis();
        while(chan.read(buff)>=0 || buff.position() > 0) {
            buff.flip();
            fc.write(buff);
            buff.compact();
        }
        chan.close();
        fc.close();
        serverChan.close();
        end = System.currentTimeMillis();
        System.out.println("Network NIO transfer time = "+(end-start)+"ms");
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Test completed!");
}

static class Client implements Runnable {

    public void run() {
        try {
            System.out.println("Client I/O initiating...");
            Socket sock = new Socket("localhost", 5555);
            System.out.println("Client connected to server successfully!");
            OutputStream os = sock.getOutputStream();
            File input = new File(System.getProperty("user.home")+"/Documents/clip0025.avi");
            FileInputStream fis = new FileInputStream(input);
            byte[] data = new byte[1024];
            int len=0;
            int tot=0;
            int perc=0;
            while((len=fis.read(data))>0) {
                os.write(data, 0, len);
                os.flush();
                tot+=len;
                int prev = perc;
                perc = getPercentage(tot, input.length());
                if(perc !=prev && (perc == 10 || perc == 25 || perc == 50 || perc == 75 || perc == 98))
                    System.out.println("Client reporting: "+perc+"% read");
            }
            os.close();
            fis.close();
            sock.close();

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Client NIO initiating...");
            SocketChannel sc = SocketChannel.open();
            boolean connected = sc.connect(new InetSocketAddress("localhost",5555));
            if(!connected)
                connected = sc.finishConnect();
            if(!connected)
                throw(new IOException("Client failed to connect"));
            System.out.println("Client channel connected");
            sc.configureBlocking(false);
            FileChannel fc = (FileChannel) Files.newByteChannel(input.toPath(), StandardOpenOption.READ);
            ByteBuffer buff = ByteBuffer.allocate(1024);
            len=0;
            tot=0;
            while((len=fc.read(buff))>=0||buff.position()>0) {
                buff.flip();
                sc.write(buff);
                buff.compact();
                tot+=len;
                int prev = perc;
                perc = getPercentage(tot, input.length());
                if(perc !=prev && (perc == 10 || perc == 25 || perc == 50 || perc == 75 || perc == 98))
                    System.out.println("Client reporting: "+perc+"% read");
            }
            sc.close();
            fc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

附加信息:

戴尔 Studio XPS 435MT 上的 Windows Vista (SP2)

第一代 i7 四核处理器 2.67GHz

6GB RAM

64 位架构


1
我并不认为这个基准测试部分是公平的 - 在Java中,你确实需要做一些像预热JVM之类的事情。你可以尝试使用像http://code.google.com/p/caliper/这样的基准测试工具。 - Louis Wasserman
1
使用由了解JVM的人构建的基准测试框架。不要编写自己的“操作计时”代码。出错的方式比正确的方式多得多。 - Louis Wasserman
4
你处理了多少个同时连接?Java NIO主要设计是为了避免“一个线程对应一个客户端”的方法。一个真正的NIO基准测试会涉及许多客户端同时连接到同一个服务器实例。 - André Caron
3
NIO的核心目标是解决传统IO在尝试处理5000个以上客户端时出现的可扩展性问题。这个基准测试完全没有意义。 - Perception
这并不意味着基准测试毫无意义。它比较了在较小规模的网络应用中使用I/O和NIO的实用性。目标是看看在这些情况下NIO是否仍然表现更好。 - bgroenks
显示剩余2条评论
1个回答

4

建议

  • 尝试将阻塞IO与阻塞NIO进行比较。您的代码将更短。如果要测试IO,请在客户端和服务器上使用IO。如果要使用NIO,则两端都要使用。
  • 使用直接ByteBuffer。
  • 不要读/写文件,因为它们不是基准测试的一部分,而且可能会更慢。只需传递空白数据块。
  • 尝试不同的块大小,例如8 KB。
  • 考虑要交换的数据类型。例如,ByteBuffer可能使读取int和long更有效率。
  • 报告带宽数字。我期望在loopback上看到1-3 GB / sec之间的数字。

http://vanillajava.blogspot.com/2010/07/java-nio-is-faster-than-java-io-for.html


你可能会觉得这个链接很有趣。 - Peter Lawrey
您是否建议使用两个独立的JVM来测试I/O和NIO,并分别进行预热? - bgroenks
将“主”类分开,在相同的热身时间内运行。即针对您的应用程序进行现实的设置。 - Peter Lawrey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接