java - Android IO 慢?

标签 java android io fat

这应该显示内部和外部内存速度,但不幸的是它说是 0.02 或 0.04 MB/s?这是 Android 中效率低下的表现,还是编码错误?

findViewById(R.id.buttonStorageSpeed).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                double SDSpeed = MBPSTest(getExternalCacheDir()); // /sdcard
                double MemSpeed = MBPSTest(getCacheDir());        // /data/data
                final AlertDialog dialog = new AlertDialog.Builder(thisContext)
                .setTitle("Memory speed")
                .setMessage( "Internal:"+String.valueOf(MemSpeed) + "\n"  + "SD:"+String.valueOf(SDSpeed))
                .create();
                dialog.show();
            }
        });




/**
     * Test MB/s write speed in some directory.
     * Writes 4MB, deletes it after.
     * @param outdir
     * @return
     */
    private double MBPSTest(File outDir) {

        long start = System.currentTimeMillis();
        try {
            for (int fnum = 0; fnum < 1024; fnum++) {
                File out = new File(outDir,"TESTspeed"+String.valueOf(fnum));
                FileOutputStream fos = new FileOutputStream(out);

                //Write 4k files
                for (int i=0; i < 1024; i++) {
                    fos.write(65);//A
                    fos.write(69);//E
                    fos.write(73);//I
                    fos.write(79);//O
                }
                fos.flush();
                fos.close();
                //System.out.println("Wrote file.");
            }
            //Wrote 4MB

            //Toast.makeText(getApplicationContext(), "Wrote External at: "+String.valueOf(4.0 / (elapsed/1000.0) )+" MB/S", Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return 0;
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }

        long elapsed = System.currentTimeMillis() - start;

        //Clean up:
        for (int fnum = 0; fnum < 1024; fnum++) {
            File out = new File(outDir, "TESTspeed"+String.valueOf(fnum));
            out.delete();
        }
        // 4 MB / (seconds)
        return 4.0 / (elapsed/1000.0);
    }

最佳答案

除了 Jonathon 提到的频繁打开和关闭文件的开销之外,您还调用 write(int)对于每个字节。

使用write(byte[])使用大缓冲区,或使用 BufferedOutputStream包裹 FileOutputStreamFileOutputStream可能有一些缓冲已经存在,但同样也可能没有。您可能会发现,一旦写入操作较少(但数据量仍然相同),速度就会快得多

关于java - Android IO 慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23852928/

相关文章:

android - activity 和 fragment 之间的生命周期

c++ - 在吃 EOF 后重用 std::cin

python - 如何在Python脚本中实现触发器

Java 服务器 - 多个客户端处理 - 使用线程是最佳选择吗?

java - 初始化字符数组

java - 如何向 JPanel 添加图像?

android - 如何在android系统状态栏中显示文字

Android 和 Live 555 媒体兼容性

c - c中的非阻塞i/o? ( window )

java - 在 proxypassreverse 设置中从 url 中删除应用程序名称