所以我正在为 Android 创建一个基准测试应用程序。现在我正在尝试添加测试内部存储读/写速度的能力。为了测试读取速度,我首先创建了一个文件(几兆字节)。接下来,我在 5 秒内尽可能多地读回文件,然后计算速度。
下面是演示我的代码的简化版本的示例代码。我从代码中得到的输出(在 Galaxy S4 上)是:
File Size (should be 4096kb): 4096kb
Total Read: 3137792 MB
Read Rate: 612.85 MB/sec
这显然太快了(我希望它在 30-60MB 范围内)。
测试代码:
private void readTest()
{
final int FILE_SIZE = 1024 * 1024 * 4;
final int CHUNK_SIZE = 1024 * 128;
final int CHUNK_NUM = FILE_SIZE / CHUNK_SIZE;
final int READ_DURATION = 5000;
File outputDir = Globals.getContext().getCacheDir();
try
{
File tempFile = File.createTempFile("InternalStorageRead", "tmp", outputDir);
// Generate some data to write to temp file
byte[] buffer = new byte[CHUNK_SIZE];
for (int i = 0; i < CHUNK_SIZE; i++)
{
buffer[i] = (byte)((i % 256) - 128);
}
// Write generated data into file
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tempFile));
for (int i = 0; i < CHUNK_NUM; i++)
{
bos.write(buffer);
bos.flush();
}
bos.close();
System.out.println("File Size (should be " + (FILE_SIZE / 1024) + "kb): " + (tempFile.length() / 1024) + "kb");
long startTimeMS = System.currentTimeMillis();
FileInputStream is = new FileInputStream(tempFile);
long bytesRead = 0;
while (System.currentTimeMillis() - startTimeMS < READ_DURATION)
{
for (int i = 0; i < 10; i++)
{
int read = is.read(buffer);
if (read > 0)
{
bytesRead += read;
}
else
{
// EOF - start reading again from beginning
is.close();
is = new FileInputStream(tempFile);
}
}
}
is.close();
double mb = bytesRead / (1024.0 * 1024.0);
System.out.println("Total Read: " + (bytesRead / 1024) + " MB");
double readRate = mb / (READ_DURATION / 1000.0);
System.out.println("Read Rate: " + readRate + " MB/sec");
}
catch (IOException e1)
{
e1.printStackTrace();
return;
}
}
似乎我的代码搞砸了(我错过了一些东西,或者编译器优化),或者它与 Android 有什么关系?像内存缓存或类似的东西。