vendredi 23 janvier 2015

Latency spikes in android when writting to file

I am running some performance tests and see some spikes in my tests results. This is the code I use to measure the time of the writing to file.



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();
}
}


}


Mostly the time it takes to write is ~0.1-0.2ms but there are spikes which takes 10+ ms and can not figure out what the cause of this is. I can not link the graph here right now as I am a new user here.


I am really stuck with this any ideas?.


Aucun commentaire:

Enregistrer un commentaire