My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* Copyright (c) 2011. Peter Lawrey
*
* "THE BEER-WARE LICENSE" (Revision 128)
* As long as you retain this notice you can do whatever you want with this stuff.
* If we meet some day, and you think this stuff is worth it, you can buy me a beer in return
* There is no warranty.
*/

package com.google.code.java.core.math;

import java.math.BigDecimal;

public class RoundingPerformanceMain {
public static void main(String... args) {
longCastPerf();
mathRoundPerf();
bidDecimalSetScalePerf();
}

private static double longCastPerf() {
double sum = 0; // to avoid micro-optimisation.
final int runs = 160 * 1000 * 1000; // about 1 second.
long start = System.nanoTime();
for (int i = 0; i < runs; i++) {
double d = i * 0.01;
sum += roundToTwoPlacesCast(d);
}
long time = System.nanoTime() - start;
System.out.printf("Took an average of %,d ns for rounding using cast%n", time / runs);
return sum;
}

private static double mathRoundPerf() {
double sum = 0; // to avoid micro-optimisation.
final int runs = 50 * 1000 * 1000; // about one second.
long start = System.nanoTime();
for (int i = 0; i < runs; i++) {
double d = i * 0.01;
sum += roundToTwoPlacesMath(d);
}
long time = System.nanoTime() - start;
System.out.printf("Took an average of %,d ns for rounding using Math.round%n", time / runs);
return sum;
}

private static double bidDecimalSetScalePerf() {
double sum = 0; // to avoid micro-optimisation.
final int runs = 1000 * 1000; // about 1 second.
long start = System.nanoTime();
for (int i = 0; i < runs; i++) {
double d = i * 0.01;
sum += roundToTwoPlacesBigDecimal(d);
}
long time = System.nanoTime() - start;
System.out.printf("Took an average of %,d ns for rounding using BigDecimal.setScale%n", time / runs);
return sum;
}

public static double roundToTwoPlacesCast(double d) {
return ((long) (d < 0 ? d * 100 - 0.5 : d * 100 + 0.5)) / 100.0;
}

public static double roundToTwoPlacesMath(double d) {
return Math.round(d * 100) / 100.0;
}

public static double roundToTwoPlacesBigDecimal(double d) {
return new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
}

Change log

r58 by peter.lawrey on Aug 30, 2011   Diff
Beerware licensing.
Go to: 
Project members, sign in to write a code review

Older revisions

r53 by peter.lawrey on Aug 18, 2011   Diff
Test to show thread safety.
r52 by peter.lawrey on Aug 18, 2011   Diff
Test to show thread safety.
All revisions of this file

File info

Size: 2290 bytes, 71 lines
Powered by Google Project Hosting