changeset 410:e1a5e5460654

Update ResultFormat APIs: make implementations private, add the PrintWriter-accepting ResultFormatFactory methods.
author shade
date Wed, 19 Feb 2014 15:50:56 +0400
parents 433a268f4a26
children b396331bc871
files jmh-core/src/main/java/org/openjdk/jmh/output/results/JSONResultFormat.java jmh-core/src/main/java/org/openjdk/jmh/output/results/NoneResultFormat.java jmh-core/src/main/java/org/openjdk/jmh/output/results/ResultFormat.java jmh-core/src/main/java/org/openjdk/jmh/output/results/ResultFormatFactory.java jmh-core/src/main/java/org/openjdk/jmh/output/results/XSVResultFormat.java jmh-core/src/test/java/org/openjdk/jmh/output/results/ResultFormatTest.java
diffstat 6 files changed, 216 insertions(+), 155 deletions(-) [+]
line wrap: on
line diff
--- a/jmh-core/src/main/java/org/openjdk/jmh/output/results/JSONResultFormat.java	Tue Feb 18 19:26:04 2014 +0400
+++ b/jmh-core/src/main/java/org/openjdk/jmh/output/results/JSONResultFormat.java	Wed Feb 19 15:50:56 2014 +0400
@@ -31,19 +31,18 @@
 import org.openjdk.jmh.runner.BenchmarkRecord;
 import org.openjdk.jmh.util.internal.Statistics;
 
-import java.io.IOException;
 import java.io.PrintWriter;
 import java.io.StringWriter;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Map;
 
-public class JSONResultFormat implements ResultFormat {
+class JSONResultFormat implements ResultFormat {
 
-    private final String output;
+    private final PrintWriter out;
 
-    public JSONResultFormat(String output) {
-        this.output = output;
+    public JSONResultFormat(PrintWriter out) {
+        this.out = out;
     }
 
     @Override
@@ -51,98 +50,91 @@
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
 
-            boolean first = true;
+        boolean first = true;
 
-            pw.println("[");
-            for (BenchmarkRecord br : results.keySet()) {
-                if (first) {
-                    first = false;
-                } else {
-                    pw.println(",");
+        pw.println("[");
+        for (BenchmarkRecord br : results.keySet()) {
+            if (first) {
+                first = false;
+            } else {
+                pw.println(",");
+            }
+
+            RunResult runResult = results.get(br);
+
+            pw.println("{");
+            pw.println("\"benchmark\" : \"" + br.getUsername() + "\",");
+            pw.println("\"mode\" : \"" + br.getMode().shortLabel() + "\",");
+            pw.println("\"threads\" : " + runResult.getParams().getThreads() + ",");
+            pw.println("\"forks\" : " + runResult.getParams().getForks() + ",");
+            pw.println("\"warmupIterations\" : " + runResult.getParams().getWarmup().getCount() + ",");
+            pw.println("\"warmupTime\" : \"" + runResult.getParams().getWarmup().getTime() + "\",");
+            pw.println("\"measurementIterations\" : " + runResult.getParams().getMeasurement().getCount() + ",");
+            pw.println("\"measurementTime\" : \"" + runResult.getParams().getMeasurement().getTime() + "\",");
+
+            if (!br.getActualParams().isEmpty()) {
+                pw.println("\"params\" : {");
+                pw.println(emitParams(br.getActualParams()));
+                pw.println("},");
+            }
+
+            pw.println("\"primaryMetric\" : {");
+            pw.println("\"score\" : " + emit(runResult.getPrimaryResult().getScore()) + ",");
+            pw.println("\"scoreError\" : " + emit(runResult.getPrimaryResult().getStatistics().getMeanErrorAt(0.999)) + ",");
+            pw.println("\"scoreConfidence\" : " + emit(runResult.getPrimaryResult().getStatistics().getConfidenceIntervalAt(0.999)) + ",");
+            pw.println(emitPercentiles(runResult.getPrimaryResult().getStatistics()));
+            pw.println("\"scoreUnit\" : \"" + runResult.getPrimaryResult().getScoreUnit() + "\",");
+            pw.println("\"rawData\" :");
+
+            {
+                Collection<String> l1 = new ArrayList<String>();
+                for (BenchResult benchResult : runResult.getRawBenchResults()) {
+                    Collection<String> scores = new ArrayList<String>();
+                    for (Result r : benchResult.getRawPrimaryResults()) {
+                        scores.add(emit(r.getScore()));
+                    }
+                    l1.add(printMultiple(scores, "[", "]"));
+                }
+                pw.println(printMultiple(l1, "[", "]"));
+                pw.println("},");
+            }
+
+            Collection<String> secondaries = new ArrayList<String>();
+            for (String secondaryName : runResult.getSecondaryResults().keySet()) {
+                Result result = runResult.getSecondaryResults().get(secondaryName);
+
+                StringBuilder sb = new StringBuilder();
+                sb.append("\"").append(secondaryName).append("\" : {");
+                sb.append("\"score\" : ").append(emit(result.getScore())).append(",");
+                sb.append("\"scoreError\" : ").append(emit(result.getStatistics().getMeanErrorAt(0.999))).append(",");
+                sb.append("\"scoreConfidence\" : ").append(emit(result.getStatistics().getConfidenceIntervalAt(0.999))).append(",");
+                sb.append(emitPercentiles(result.getStatistics()));
+                sb.append("\"scoreUnit\" : \"").append(result.getScoreUnit()).append("\",");
+                sb.append("\"rawData\" :");
+
+                Collection<String> l2 = new ArrayList<String>();
+                for (BenchResult benchResult : runResult.getRawBenchResults()) {
+                    Collection<String> scores = new ArrayList<String>();
+                    for (Result r : benchResult.getRawSecondaryResults().get(secondaryName)) {
+                        scores.add(emit(r.getScore()));
+                    }
+                    l2.add(printMultiple(scores, "[", "]"));
                 }
 
-                RunResult runResult = results.get(br);
+                sb.append(printMultiple(l2, "[", "]"));
+                sb.append("}");
+                secondaries.add(sb.toString());
+            }
+            pw.println("\"secondaryMetrics\" : {");
+            pw.println(printMultiple(secondaries, "", ""));
+            pw.println("}");
 
-                pw.println("{");
-                pw.println("\"benchmark\" : \"" + br.getUsername() + "\",");
-                pw.println("\"mode\" : \"" + br.getMode().shortLabel() + "\",");
-                pw.println("\"threads\" : " + runResult.getParams().getThreads() + ",");
-                pw.println("\"forks\" : " + runResult.getParams().getForks() + ",");
-                pw.println("\"warmupIterations\" : " + runResult.getParams().getWarmup().getCount() + ",");
-                pw.println("\"warmupTime\" : \"" + runResult.getParams().getWarmup().getTime() + "\",");
-                pw.println("\"measurementIterations\" : " + runResult.getParams().getMeasurement().getCount() + ",");
-                pw.println("\"measurementTime\" : \"" + runResult.getParams().getMeasurement().getTime() + "\",");
+            pw.println("}");
 
-                if (!br.getActualParams().isEmpty()) {
-                    pw.println("\"params\" : {");
-                    pw.println(emitParams(br.getActualParams()));
-                    pw.println("},");
-                }
+        }
+        pw.println("]");
 
-                pw.println("\"primaryMetric\" : {");
-                pw.println("\"score\" : " + emit(runResult.getPrimaryResult().getScore()) + ",");
-                pw.println("\"scoreError\" : " + emit(runResult.getPrimaryResult().getStatistics().getMeanErrorAt(0.999)) + ",");
-                pw.println("\"scoreConfidence\" : " + emit(runResult.getPrimaryResult().getStatistics().getConfidenceIntervalAt(0.999)) + ",");
-                pw.println(emitPercentiles(runResult.getPrimaryResult().getStatistics()));
-                pw.println("\"scoreUnit\" : \"" + runResult.getPrimaryResult().getScoreUnit() + "\",");
-                pw.println("\"rawData\" :");
-
-                {
-                    Collection<String> l1 = new ArrayList<String>();
-                    for (BenchResult benchResult : runResult.getRawBenchResults()) {
-                        Collection<String> scores = new ArrayList<String>();
-                        for (Result r : benchResult.getRawPrimaryResults()) {
-                            scores.add(emit(r.getScore()));
-                        }
-                        l1.add(printMultiple(scores, "[", "]"));
-                    }
-                    pw.println(printMultiple(l1, "[", "]"));
-                    pw.println("},");
-                }
-
-                Collection<String> secondaries = new ArrayList<String>();
-                for (String secondaryName : runResult.getSecondaryResults().keySet()) {
-                    Result result = runResult.getSecondaryResults().get(secondaryName);
-
-                    StringBuilder sb = new StringBuilder();
-                    sb.append("\"").append(secondaryName).append("\" : {");
-                    sb.append("\"score\" : ").append(emit(result.getScore())).append(",");
-                    sb.append("\"scoreError\" : ").append(emit(result.getStatistics().getMeanErrorAt(0.999))).append(",");
-                    sb.append("\"scoreConfidence\" : ").append(emit(result.getStatistics().getConfidenceIntervalAt(0.999))).append(",");
-                    sb.append(emitPercentiles(result.getStatistics()));
-                    sb.append("\"scoreUnit\" : \"").append(result.getScoreUnit()).append("\",");
-                    sb.append("\"rawData\" :");
-
-                    Collection<String> l2 = new ArrayList<String>();
-                    for (BenchResult benchResult : runResult.getRawBenchResults()) {
-                        Collection<String> scores = new ArrayList<String>();
-                        for (Result r : benchResult.getRawSecondaryResults().get(secondaryName)) {
-                            scores.add(emit(r.getScore()));
-                        }
-                        l2.add(printMultiple(scores, "[", "]"));
-                    }
-
-                    sb.append(printMultiple(l2, "[", "]"));
-                    sb.append("}");
-                    secondaries.add(sb.toString());
-                }
-                pw.println("\"secondaryMetrics\" : {");
-                pw.println(printMultiple(secondaries, "", ""));
-                pw.println("}");
-
-                pw.println("}");
-
-            }
-            pw.println("]");
-
-        try {
-            PrintWriter out = new PrintWriter(output);
-            out.println(tidy(sw.toString()));
-            out.flush();
-            out.close();
-        } catch (IOException e) {
-            throw new IllegalStateException(e);
-        }
+        out.println(tidy(sw.toString()));
     }
 
     private String emitParams(ActualParams params) {
@@ -164,7 +156,7 @@
         StringBuilder sb = new StringBuilder();
         sb.append("\"scorePercentiles\" : {");
         boolean firstPercentile = true;
-        for (double p : new double[] {0.00, 0.50, 0.90, 0.95, 0.99, 0.999, 0.9999, 0.99999, 0.999999, 1.0}) {
+        for (double p : new double[]{0.00, 0.50, 0.90, 0.95, 0.99, 0.999, 0.9999, 0.99999, 0.999999, 1.0}) {
             if (firstPercentile) {
                 firstPercentile = false;
             } else {
@@ -172,7 +164,7 @@
             }
 
             double v = stats.getPercentile(p * 100);
-            sb.append(String.format("\"%.4f\" : %.3f", p*100, v));
+            sb.append(String.format("\"%.4f\" : %.3f", p * 100, v));
         }
         sb.append("},");
         return sb.toString();
--- a/jmh-core/src/main/java/org/openjdk/jmh/output/results/NoneResultFormat.java	Tue Feb 18 19:26:04 2014 +0400
+++ b/jmh-core/src/main/java/org/openjdk/jmh/output/results/NoneResultFormat.java	Wed Feb 19 15:50:56 2014 +0400
@@ -29,7 +29,7 @@
 
 import java.util.Map;
 
-public class NoneResultFormat implements ResultFormat {
+class NoneResultFormat implements ResultFormat {
     @Override
     public void writeOut(Map<BenchmarkRecord, RunResult> results) {
         // do nothing
--- a/jmh-core/src/main/java/org/openjdk/jmh/output/results/ResultFormat.java	Tue Feb 18 19:26:04 2014 +0400
+++ b/jmh-core/src/main/java/org/openjdk/jmh/output/results/ResultFormat.java	Wed Feb 19 15:50:56 2014 +0400
@@ -27,6 +27,7 @@
 import org.openjdk.jmh.logic.results.RunResult;
 import org.openjdk.jmh.runner.BenchmarkRecord;
 
+import java.io.PrintWriter;
 import java.util.Map;
 
 public interface ResultFormat {
--- a/jmh-core/src/main/java/org/openjdk/jmh/output/results/ResultFormatFactory.java	Tue Feb 18 19:26:04 2014 +0400
+++ b/jmh-core/src/main/java/org/openjdk/jmh/output/results/ResultFormatFactory.java	Wed Feb 19 15:50:56 2014 +0400
@@ -24,11 +24,51 @@
  */
 package org.openjdk.jmh.output.results;
 
+import org.openjdk.jmh.logic.results.RunResult;
+import org.openjdk.jmh.runner.BenchmarkRecord;
+
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Map;
+
 public class ResultFormatFactory {
 
     private ResultFormatFactory() {}
 
-    public static ResultFormat getInstance(ResultFormatType type, String output) {
+    /**
+     * Get the instance of ResultFormat of given type which writes the result to file
+     * @param type result format type
+     * @param file target file
+     * @return result format
+     */
+    public static ResultFormat getInstance(final ResultFormatType type, final String file) {
+        return new ResultFormat() {
+            @Override
+            public void writeOut(Map<BenchmarkRecord, RunResult> results) {
+                try {
+                    PrintWriter pw = new PrintWriter(file);
+                    ResultFormat rf = getInstance(type, pw);
+                    rf.writeOut(results);
+                    pw.flush();
+                    pw.close();
+                } catch (IOException e) {
+                    throw new IllegalStateException(e);
+                }
+            }
+        };
+    }
+
+    /**
+     * Get the instance of ResultFormat of given type which write the result to writer.
+     * It is a user responsibility to initialize and finish the writer as appropriate.
+     *
+     * @param type result format type
+     * @param writer target writer
+     * @return result format.
+     */
+    public static ResultFormat getInstance(ResultFormatType type, PrintWriter writer) {
         switch (type) {
             case NONE:
                 return new NoneResultFormat();
@@ -36,7 +76,7 @@
                 /*
                  * CSV formatter follows the provisions of http://tools.ietf.org/html/rfc4180
                  */
-                return new XSVResultFormat(output, ",");
+                return new XSVResultFormat(writer, ",");
             case SCSV:
                 /*
                  *    Since some implementations, notably Excel, think it is a good
@@ -44,9 +84,9 @@
                  *    comma in some locales, this is the specialised
                  *     Semi-Colon Separated Values formatter.
                  */
-                return new XSVResultFormat(output, ";");
+                return new XSVResultFormat(writer, ";");
             case JSON:
-                return new JSONResultFormat(output);
+                return new JSONResultFormat(writer);
             default:
                 throw new IllegalStateException("Unsupported result format: " + type);
         }
--- a/jmh-core/src/main/java/org/openjdk/jmh/output/results/XSVResultFormat.java	Tue Feb 18 19:26:04 2014 +0400
+++ b/jmh-core/src/main/java/org/openjdk/jmh/output/results/XSVResultFormat.java	Wed Feb 19 15:50:56 2014 +0400
@@ -30,75 +30,59 @@
 import java.io.BufferedWriter;
 import java.io.FileWriter;
 import java.io.IOException;
+import java.io.PrintWriter;
 import java.util.Map;
 
-public class XSVResultFormat implements ResultFormat {
+class XSVResultFormat implements ResultFormat {
 
-    private final String output;
+    private final PrintWriter pw;
     private final String delimiter;
 
-    public XSVResultFormat(String output, String delimiter) {
-        this.output = output;
+    public XSVResultFormat(PrintWriter pw, String delimiter) {
+        this.pw = pw;
         this.delimiter = delimiter;
     }
 
     @Override
     public void writeOut(Map<BenchmarkRecord, RunResult> results) {
-        FileWriter fw = null;
-        try  {
-            fw = new FileWriter(output);
-            BufferedWriter bw = new BufferedWriter(fw);
+        pw.write("\"Benchmark\"");
+        pw.write(delimiter);
+        pw.write("\"Mode\"");
+        pw.write(delimiter);
+        pw.write("\"Threads\"");
+        pw.write(delimiter);
+        pw.write("\"Samples\"");
+        pw.write(delimiter);
+        pw.write("\"Mean\"");
+        pw.write(delimiter);
+        pw.write("\"Mean Error (99.9%)\"");
+        pw.write(delimiter);
+        pw.write("\"Unit\"");
+        pw.write("\r\n");
 
-            bw.write("\"Benchmark\"");
-            bw.write(delimiter);
-            bw.write("\"Mode\"");
-            bw.write(delimiter);
-            bw.write("\"Threads\"");
-            bw.write(delimiter);
-            bw.write("\"Samples\"");
-            bw.write(delimiter);
-            bw.write("\"Mean\"");
-            bw.write(delimiter);
-            bw.write("\"Mean Error (99.9%)\"");
-            bw.write(delimiter);
-            bw.write("\"Unit\"");
-            bw.write("\r\n");
+        for (BenchmarkRecord br : results.keySet()) {
+            RunResult runResult = results.get(br);
 
-            for (BenchmarkRecord br : results.keySet()) {
-                RunResult runResult = results.get(br);
-
-                bw.write("\"");
-                bw.write(br.getUsername());
-                bw.write("\"");
-                bw.write(delimiter);
-                bw.write("\"");
-                bw.write(br.getMode().shortLabel());
-                bw.write("\"");
-                bw.write(delimiter);
-                bw.write(String.valueOf(runResult.getParams().getThreads()));
-                bw.write(delimiter);
-                bw.write(String.valueOf(runResult.getPrimaryResult().getStatistics().getN()));
-                bw.write(delimiter);
-                bw.write(String.valueOf(runResult.getPrimaryResult().getStatistics().getMean()));
-                bw.write(delimiter);
-                bw.write(String.valueOf(runResult.getPrimaryResult().getStatistics().getMeanErrorAt(0.999)));
-                bw.write(delimiter);
-                bw.write("\"");
-                bw.write(runResult.getPrimaryResult().getScoreUnit());
-                bw.write("\"");
-                bw.write("\r\n");
-            }
-            bw.close();
-        } catch (IOException e) {
-            throw new IllegalStateException(e);
-        } finally {
-            if (fw != null) {
-                try {
-                    fw.close();
-                } catch (IOException e) {
-                    // do nothing
-                }
-            }
+            pw.write("\"");
+            pw.write(br.getUsername());
+            pw.write("\"");
+            pw.write(delimiter);
+            pw.write("\"");
+            pw.write(br.getMode().shortLabel());
+            pw.write("\"");
+            pw.write(delimiter);
+            pw.write(String.valueOf(runResult.getParams().getThreads()));
+            pw.write(delimiter);
+            pw.write(String.valueOf(runResult.getPrimaryResult().getStatistics().getN()));
+            pw.write(delimiter);
+            pw.write(String.valueOf(runResult.getPrimaryResult().getStatistics().getMean()));
+            pw.write(delimiter);
+            pw.write(String.valueOf(runResult.getPrimaryResult().getStatistics().getMeanErrorAt(0.999)));
+            pw.write(delimiter);
+            pw.write("\"");
+            pw.write(runResult.getPrimaryResult().getScoreUnit());
+            pw.write("\"");
+            pw.write("\r\n");
         }
 
     }
--- a/jmh-core/src/test/java/org/openjdk/jmh/output/results/ResultFormatTest.java	Tue Feb 18 19:26:04 2014 +0400
+++ b/jmh-core/src/test/java/org/openjdk/jmh/output/results/ResultFormatTest.java	Wed Feb 19 15:50:56 2014 +0400
@@ -39,9 +39,11 @@
 
 import java.io.BufferedReader;
 import java.io.File;
+import java.io.FileOutputStream;
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
+import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Map;
@@ -119,6 +121,20 @@
     }
 
     @Test
+    public void jsonTest_Stream() throws IOException {
+        String actualFile = File.createTempFile("jmh", "test").getAbsolutePath();
+
+        PrintWriter pw = new PrintWriter(actualFile);
+        ResultFormatFactory.getInstance(
+                    ResultFormatType.JSON,
+                    pw)
+                .writeOut(getStub());
+        pw.close();
+
+        compare(actualFile, "output-golden.json");
+    }
+
+    @Test
     public void csvTest() throws IOException {
         String actualFile = File.createTempFile("jmh", "test").getAbsolutePath();
 
@@ -131,6 +147,20 @@
     }
 
     @Test
+    public void csvTest_Stream() throws IOException {
+        String actualFile = File.createTempFile("jmh", "test").getAbsolutePath();
+
+        PrintWriter pw = new PrintWriter(actualFile);
+        ResultFormatFactory.getInstance(
+                    ResultFormatType.CSV,
+                    pw)
+                .writeOut(getStub());
+        pw.close();
+
+        compare(actualFile, "output-golden.csv");
+    }
+
+    @Test
     public void scsvTest() throws IOException {
         String actualFile = File.createTempFile("jmh", "test").getAbsolutePath();
 
@@ -142,4 +172,18 @@
         compare(actualFile, "output-golden.scsv");
     }
 
+    @Test
+    public void scsvTest_Stream() throws IOException {
+        String actualFile = File.createTempFile("jmh", "test").getAbsolutePath();
+
+        PrintWriter pw = new PrintWriter(actualFile);
+        ResultFormatFactory.getInstance(
+                    ResultFormatType.SCSV,
+                    actualFile)
+                .writeOut(getStub());
+        pw.close();
+
+        compare(actualFile, "output-golden.scsv");
+    }
+
 }