#юнит_тесты #java #junit
Я начинаю осваивать Java, так что без рук).
Мне нужно на простой программе протестировать скорость роботы и затраты памяти.
Как в Java можно это сделать?
import java.io.*;
class SearchPhrase {
// walk to root way
public void walk(String path, String whatFind) throws IOException {
File root = new File(path);
File[] list = root.listFiles();
for (File titleName : list) {
if (titleName.isDirectory()) {
walk(titleName.getAbsolutePath(), whatFind);
} else {
if (read(titleName.getAbsolutePath()).contains(whatFind)) {
System.out.println("File: " + titleName.getAbsolutePath());
}
}
}
}
// Read file as one line
public static String read(String fileName) {
StringBuilder strBuider = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new FileReader(new File(
fileName)));
String strInput;
while ((strInput = in.readLine()) != null) {
strBuider.append(strInput);
strBuider.append("\n");
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return strBuider.toString();
}
public static void main(String[] args) {
SearchPhrase example = new SearchPhrase();
try {
example.walk("C:\\Documents and Settings\\User\\Java", "programmed");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Ответы
Ответ 1
Это решение разработано самим автором вопроса, но он оставил его в вопросе. Время работы программы: public static void main(String[] args) { SearchPhrase example = new SearchPhrase(); long startTime = System.currentTimeMillis(); try { example.walk("E:\\Document\\Effortless English\\Level 3", "spot"); } catch (IOException e) { e.printStackTrace(); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; System.out.println(elapsedTime); } Потребление памяти: package task; public class SearchPhrase_PerformanceTest { private static final long MEGABYTE = 1024L * 1024L; public static long bytesToMegabytes(long bytes) { return bytes / MEGABYTE; } public static void main(String[] args) { SearchPhrase example = new SearchPhrase(); example.askUserPathAndWord(); // Get the Java runtime Runtime runtime = Runtime.getRuntime(); // Run the garbage collector runtime.gc(); // Calculate the used memory long memory = runtime.totalMemory() - runtime.freeMemory(); System.out.println("Used memory is bytes: " + memory); System.out.println("Used memory is megabytes: " + bytesToMegabytes(memory)); } } Все просто и понятно ;)
Комментариев нет:
Отправить комментарий