Advertisement
Guest User

Untitled

a guest
Sep 10th, 2012
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.55 KB | None | 0 0
  1. package SetExercise;
  2.  
  3. import java.io.*;
  4. import java.util.*;
  5.  
  6. public class SetBenchmark {
  7.  
  8.     public static void main(String[] args) {
  9.         String path = "war-and-peace.txt";
  10.         HashSet<String> init = new HashSet<>();
  11.         // To cache the file so that Benchmarks should be about Equal.
  12.         fileToSet(path, init);
  13.        
  14.         HashSet<String> hs = new HashSet<>();
  15.         TreeSet<String> ts = new TreeSet<>();
  16.         long start = System.nanoTime();
  17.         for(int i = 0; i < 1000; i++) {
  18.             fileToSet(path,hs);
  19.             hs.clear();
  20.         }
  21.         long end = System.nanoTime();
  22.         long elapsed = (end - start) / 1000;
  23.         System.out.println("Total time HashSet (ns): " + elapsed);
  24.        
  25.         start = System.nanoTime();
  26.         for(int i = 0; i < 1000; i++) {
  27.             fileToSet(path, ts);
  28.             ts.clear();
  29.         }
  30.         end = System.nanoTime();
  31.        
  32.         elapsed = (end - start) / 1000;
  33.         System.out.println("Total time TreeSet (ns): " + elapsed);
  34.     }
  35.  
  36.     static void fileToSet(String path, Set<String> set) {
  37.         try {
  38.             try (BufferedReader in = new BufferedReader(new FileReader(path))) {
  39.                 String line;
  40.                 while((line = in.readLine()) != null) {
  41.                     set.add(line);
  42.                 }
  43.             }
  44.         } catch(FileNotFoundException fnfe) {
  45.             System.out.println(fnfe.getMessage());
  46.         } catch(IOException ioe) {
  47.             System.out.println(ioe.getMessage());
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement