Java 度量双精度与双精度
我编写了一个简单的基准测试,测试多个double和BigDecimal的性能。我的方法正确吗?我使用随机值是因为编译器多次优化了多个常量(例如Java 度量双精度与双精度,java,double,bigdecimal,Java,Double,Bigdecimal,我编写了一个简单的基准测试,测试多个double和BigDecimal的性能。我的方法正确吗?我使用随机值是因为编译器多次优化了多个常量(例如Math.PI*Math.E)。 但是: -我不知道在测试中生成随机数是否会破坏结果。 -在测试中创建新的BigDecimal对象也是如此 我只想测试乘法的性能(不是构造函数使用的时间) 怎样才能做到呢 import java.math.*; import java.util.*; public class DoubleVsBigDecimal {
Math.PI*Math.E
)。但是:
-我不知道在测试中生成随机数是否会破坏结果。
-在测试中创建新的
BigDecimal
对象也是如此
我只想测试乘法的性能(不是构造函数使用的时间)
怎样才能做到呢
import java.math.*;
import java.util.*;
public class DoubleVsBigDecimal
{
public static void main(String[] args)
{
Random rnd = new Random();
long t1, t2, t3;
double t;
t1 = System.nanoTime();
for(int i=0; i<1000000; i++)
{
double d1 = rnd.nextDouble();
double d2 = rnd.nextDouble();
t = d1 * d2;
}
t2 = System.nanoTime();
for(int i=0; i<1000000; i++)
{
BigDecimal bd1 = BigDecimal.valueOf(rnd.nextDouble());
BigDecimal bd2 = BigDecimal.valueOf(rnd.nextDouble());
bd1.multiply(bd2);
}
t3 = System.nanoTime();
System.out.println(String.format("%f",(t2-t1)/1e9));
System.out.println(String.format("%f",(t3-t2)/1e9));
System.out.println(String.format("%f",(double)(t3-t2)/(double)(t2-t1)));
}
}
import java.math.*;
导入java.util.*;
公共类DoubleVsBigDecimal
{
公共静态void main(字符串[]args)
{
随机rnd=新随机();
长t1、t2、t3;
双t;
t1=系统.nanoTime();
对于(inti=0;i而言,您不仅对乘法运算进行计时,还对其他事情进行计时
您需要执行以下操作:
long time = 0;
for(int i=0; i<1000000; i++) {
double d1 = rnd.nextDouble();
double d2 = rnd.nextDouble();
long start = System.nanoTime();
t = d1 * d2;
long end = System.nanoTime();
time += (end-start)
}
long meantime = time / 1000000;
long time=0;
例如,Java中的(inti=0;i基准测试非常奇怪。例如,JVM在一段代码运行多次之前不会真正完全优化它——但在优化之后进行度量更公平,因为任何生产系统都会多次调用此方法
Java基准测试还有许多其他问题。避免这些问题的最简单方法可能是使用由专家构建的Java基准测试工具,例如,您可以预先生成两个1000个双精度/大小数的集合,并在两个嵌套循环中分别相乘:
public static void main(String[] args)
{
Random rnd = new Random();
List <Double> dl = new ArrayList <Double> ();
List <BigDecimal> bdl = new ArrayList <BigDecimal> ();
for(int i=0; i<1000; i++)
{
double d = rnd.nextDouble();
dl.add (d);
bdl.add (new BigDecimal (d));
}
long t1 = System.nanoTime();
double t;
for (double d1 : dl)
for (double d2 : dl)
t = d1 * d2;
long t2 = System.nanoTime();
for (BigDecimal b1 : bdl)
for (BigDecimal b2 : bdl)
b1.multiply (b2);
long t3 = System.nanoTime();
System.out.println (String.format ("%f", (t2 - t1) / 1e9));
System.out.println (String.format ("%f", (t3 - t2) / 1e9));
System.out.println (String.format ("%f", (double) (t3 - t2) / (double) (t2 - t1)));
}
我的代码有不同的值,但也很稳定:
0,077177
1,112490
14,414710
这个关系的差别是1:4,这差不多。不像BigDecimal:double的关系那么大,但是很好---
(i386-32,客户端模式,JRE-1.6,linux,oracle,2Ghz Centrino单核)。我强烈推荐本文作为基准测试的介绍:
是否足够精确?如果足够精确,就不需要循环。实际上,如果不是循环,就不要烘焙得更精确。不-你需要平均值,以确保你得到的读数不是偶然的
0,077177
1,112490
14,414710