【发布时间】:2015-01-23 13:49:55
【问题描述】:
我正在运行一些性能测试,并在我的测试结果中看到一些峰值。 这是我用来测量写入文件时间的代码。
public class Test extends AndroidTestCase {
private DecimalFormat decimalFormat = new DecimalFormat("#.##");
private final Boolean isInternal = true;
public void testWrite() {
Thread thread = new Thread() {
public void run() {
File dummy_file = createFile("dummy2", true);
File file = createFile("normal_write", isInternal);
for (int i = 0; i < 12500; i++) {
long start = System.nanoTime();
write(dummy_file, String.valueOf(i));
long stop = System.nanoTime();
double mSec = ((double) (stop - start) / 1000000.0);
write(file, decimalFormat.format(mSec));
}
}
};
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public File createFile(String fileName, Boolean isInternal) {
deleteFile(fileName, isInternal);
try {
String file_path = "";
if(isInternal == true) {
file_path = getContext().getFilesDir().getAbsolutePath() + "/" + fileName + ".dat";
} else {
file_path = Environment.getExternalStorageDirectory() + "/" + fileName + ".dat";
}
File file = new File(file_path);
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("##;##\n" +
"@LiveGraph demo file.\n" +
"Time");
bw.newLine();
bw.close();
return file;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void deleteFile(String fileName, Boolean isInternal) {
String file_path = "";
if ( isInternal == true) {
file_path = getContext().getFilesDir().getAbsolutePath() + "/" + fileName + ".dat";
} else {
file_path = Environment.getExternalStorageDirectory() + "/" + fileName + ".dat";
}
File file = new File(file_path);
file.delete();
}
public void write(File file, String content) {
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.newLine();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
大多数情况下,写入所需的时间约为 0.1-0.2 毫秒,但有些峰值需要 10 多毫秒,无法弄清楚这是什么原因。由于我是这里的新用户,我现在无法在此处链接图表。
我真的坚持这个有什么想法吗?
这是时间测量的一部分。
0.16 0.16 0.17 0.15 0.15 2.5 0.17 0.16 0.16 0.16 0.15 0.17 0.17 0.17 0.19 0.19 0.17 0.2 0 0 4.79 0.24 0.23 0.28 0.23 0.28 0.03 0 11.23 0.16 0.15 0.18 0.16 0.16 0.17 0.16 5.84
【问题讨论】:
标签: android performance testing file-io latency