这应该显示内部和外部内存速度,但不幸的是它说它是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);
}
答案 0 :(得分:2)
除了Jonathon提到的打开和关闭文件的开销很大,你还要为每个字节调用write(int)
。
使用大缓冲区使用write(byte[])
,或使用BufferedOutputStream
包装FileOutputStream
。 可能已经在FileOutputStream
中进行了一些缓冲,但同样可能没有。您可能会发现,一旦您的写入操作较少(但数据量相同),它的很多就会更快。
答案 1 :(得分:0)
你在这里引入了大量的开销:
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
您每4k关闭并打开一次文件(每个文件1024次)。相反,你应该只在循环外一次打开它。
这还远未成为科学考验。您正在制作一堆API调用,这些调用无法显示设备的实际速度。此外,您可能会有一堆文件系统重新调整开销。
更好的方法可能是: