double の乗算と BigDecimal のパフォーマンスをテストする簡単なベンチマークを作成しました。私の方法は正しいですか?コンパイラーが乗算定数を何度も最適化したため、ランダム化された値を使用します (例: 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)));
}
}