Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package SetExercise;
- import java.io.*;
- import java.util.*;
- public class SetBenchmark {
- public static void main(String[] args) {
- String path = "war-and-peace.txt";
- HashSet<String> init = new HashSet<>();
- // To cache the file so that Benchmarks should be about Equal.
- fileToSet(path, init);
- HashSet<String> hs = new HashSet<>();
- TreeSet<String> ts = new TreeSet<>();
- long start = System.nanoTime();
- for(int i = 0; i < 1000; i++) {
- fileToSet(path,hs);
- hs.clear();
- }
- long end = System.nanoTime();
- long elapsed = (end - start) / 1000;
- System.out.println("Total time HashSet (ns): " + elapsed);
- start = System.nanoTime();
- for(int i = 0; i < 1000; i++) {
- fileToSet(path, ts);
- ts.clear();
- }
- end = System.nanoTime();
- elapsed = (end - start) / 1000;
- System.out.println("Total time TreeSet (ns): " + elapsed);
- }
- static void fileToSet(String path, Set<String> set) {
- try {
- try (BufferedReader in = new BufferedReader(new FileReader(path))) {
- String line;
- while((line = in.readLine()) != null) {
- set.add(line);
- }
- }
- } catch(FileNotFoundException fnfe) {
- System.out.println(fnfe.getMessage());
- } catch(IOException ioe) {
- System.out.println(ioe.getMessage());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement