为什么我的流复制过程在性能方面稳步降低



在复制大文件时,此代码的工作速度较慢。我做错了吗?

    InputStream ms2 = new BufferedInputStream(new FileInputStream("/home/fedd/Videos/homevid.mp4"));
    OutputStream fos2 = new BufferedOutputStream(new FileOutputStream("testfile2.mp4", true));
    try {
        int byt;
        int i = 0;
        long time = System.currentTimeMillis();
        while ((byt = ms2.read()) != -1) {
            fos2.write(byt);
            i++;
            if (i > 100000) {
                i = 0;
                long took = System.currentTimeMillis() - time;
                System.out.println("100000 bytes took " + took + " milliseconds which means " + (100000000 / took) + " bytes per second");
            }
        }
        fos2.close();
        ms2.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

我的Java是:

OpenJDK 10.0.2 2018-07-17 OpenJDK运行时环境(构建 10.0.2 13-ubuntu-1ubuntu0.18.04.4)

OpenJDK 64位服务器VM(构建10.0.2 13-ubuntu-1ubuntu0.18.04.4, 混合模式)

您需要在每次比较后重置基本'时间'。尝试使用以下方式:

if (i > 100000) {
    i = 0;
    long took = System.currentTimeMillis() - time;
    time = System.currentTimeMillis();
    System.out.println("100000 bytes took " + took + " milliseconds which means " + (100000000 / took) + " bytes per second");
}

您的性能降低,因为您的计算是错误的。对于第二个块,您正在计算第二个块大小的每秒字节,但要从两个块时间开始。尝试在long took = ...之后添加time = System.currentTimeMillis();

最新更新