blob: 291ec84752f21ce3dc2b6e6b489cb1f7bcdc8df3 [file] [log] [blame]
Paul Duffin7fc0b452015-11-10 17:45:15 +00001/*
2 * Copyright (C) 2009 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package examples;
18
19import com.google.caliper.Param;
20import com.google.caliper.Runner;
21import com.google.caliper.SimpleBenchmark;
22
23import java.util.Arrays;
24import java.util.List;
25
26/**
27 * Measures the various ways the JDK converts doubles to strings.
28 */
29public class DoubleToStringBenchmark extends SimpleBenchmark {
30 @Param Method method;
31
32 public enum Method {
33 TO_STRING {
34 @Override String convert(double d) {
35 return ((Double) d).toString();
36 }
37 @Override String convert(Double d) {
38 return d.toString();
39 }
40 },
41 STRING_VALUE_OF {
42 @Override String convert(double d) {
43 return String.valueOf(d);
44 }
45 @Override String convert(Double d) {
46 return String.valueOf(d);
47 }
48 },
49 STRING_FORMAT {
50 @Override String convert(double d) {
51 return String.format("%f", d);
52 }
53 @Override String convert(Double d) {
54 return String.format("%f", d);
55 }
56 },
57 QUOTE_TRICK {
58 @Override String convert(double d) {
59 return "" + d;
60 }
61 @Override String convert(Double d) {
62 return "" + d;
63 }
64 },
65 ;
66
67 abstract String convert(double d);
68 abstract String convert(Double d);
69 }
70
71 enum Value {
72 Pi(Math.PI),
73 NegativeZero(-0.0),
74 NegativeInfinity(Double.NEGATIVE_INFINITY),
75 NaN(Double.NaN);
76
77 final double value;
78
79 Value(double value) {
80 this.value = value;
81 }
82 }
83
84 @Param Value value;
85
86 public int timePrimitive(int reps) {
87 double d = value.value;
88 int dummy = 0;
89 for (int i = 0; i < reps; i++) {
90 dummy += method.convert(d).length();
91 }
92 return dummy;
93 }
94
95 public int timeWrapper(int reps) {
96 Double d = value.value;
97 int dummy = 0;
98 for (int i = 0; i < reps; i++) {
99 dummy += method.convert(d).length();
100 }
101 return dummy;
102 }
103
104 public static void main(String[] args) throws Exception {
105 Runner.main(DoubleToStringBenchmark.class, args);
106 }
107}