blob: d49a53d57e0ee048d1415c7310ab34430a3fd4d8 [file] [log] [blame]
Jesse Wilson1440b362009-12-15 18:54:02 -08001/*
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
Jesse Wilsonf062bf42010-01-13 17:12:18 -080017package examples;
Jesse Wilson1440b362009-12-15 18:54:02 -080018
Jesse Wilson1440b362009-12-15 18:54:02 -080019import com.google.caliper.Param;
20import com.google.caliper.Runner;
Jesse Wilsonf062bf42010-01-13 17:12:18 -080021import com.google.caliper.SimpleBenchmark;
22import com.google.common.collect.ImmutableList;
Jesse Wilson1440b362009-12-15 18:54:02 -080023import java.util.Collection;
24
25/**
26 * Measures the various ways the JDK converts primitive doubles to Strings.
27 */
28public class PrimitiveDoubleToStringBenchmark extends SimpleBenchmark {
29
30 @Param private double d;
31
Jesse Wilsonf062bf42010-01-13 17:12:18 -080032 public static final Collection<Double> dValues = ImmutableList.of(
Jesse Wilson1440b362009-12-15 18:54:02 -080033 Math.PI,
34 -0.0d,
35 Double.NEGATIVE_INFINITY,
36 Double.NaN
37 );
38
39 public int timeStringFormat(int reps) {
40 double value = d;
41 int dummy = 0;
42 for (int i = 0; i < reps; i++) {
43 dummy += String.format("%f", value).length();
44 }
45 return dummy;
46 }
47
48 public int timeToString(int reps) {
49 double value = d;
50 int dummy = 0;
51 for (int i = 0; i < reps; i++) {
52 dummy += ((Double) value).toString().length();
53 }
54 return dummy;
55 }
56
57 public int timeStringValueOf(int reps) {
58 double value = d;
59 int dummy = 0;
60 for (int i = 0; i < reps; i++) {
61 dummy += String.valueOf(value).length();
62 }
63 return dummy;
64 }
65
66 public int timeQuoteTrick(int reps) {
67 double value = d;
68 int dummy = 0;
69 for (int i = 0; i < reps; i++) {
70 dummy = ("" + value).length();
71 }
72 return dummy;
73 }
74
75 // TODO: remove this from all examples when IDE plugins are ready
76 public static void main(String[] args) throws Exception {
77 Runner.main(PrimitiveDoubleToStringBenchmark.class, args);
78 }
79}