Advertisement
Guest User

Untitled

a guest
Sep 10th, 2012
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 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> cache = new HashSet<>();
  11.         // To cache the file so that Benchmarks should be about Equal.
  12.         fileToSet(path, cache);
  13.        
  14.         HashSet<String> hs = new HashSet<>();
  15.         TreeSet<String> ts = new TreeSet<>();
  16.         long start = 0;
  17.         long end = 0;
  18.         for(int i = 0; i < 5; i++) {
  19.             start += System.nanoTime();
  20.             fileToSet(path,hs);
  21.             end += System.nanoTime();
  22.             hs = new HashSet<>();
  23.         }
  24.         start = start / 5;
  25.         end = end / 5;
  26.         long elapsed = end - start;
  27.         System.out.println("Total time HashSet (ns): " + elapsed);
  28.        
  29.         start = 0;
  30.         end = 0;
  31.         elapsed = 0;
  32.         for(int i = 0; i < 5; i++) {
  33.             start += System.nanoTime();
  34.             fileToSet(path, ts);
  35.             end += System.nanoTime();
  36.             ts = new TreeSet<>();
  37.         }
  38.         start = start / 5;
  39.         end = end / 5;
  40.         elapsed = end - start;
  41.         System.out.println("Total time TreeSet (ns): " + elapsed);
  42.     }
  43.  
  44.     static void fileToSet(String path, Set<String> set) {
  45.         try {
  46.             try (BufferedReader in = new BufferedReader(new FileReader(path))) {
  47.                 String line;
  48.                 while((line = in.readLine()) != null) {
  49.                     set.add(line);
  50.                 }
  51.             }
  52.         } catch(FileNotFoundException fnfe) {
  53.             System.out.println(fnfe.getMessage());
  54.         } catch(IOException ioe) {
  55.             System.out.println(ioe.getMessage());
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement