BigInteger 中的乘法时间
2022-09-01 23:50:28
						我的迷你基准测试:
import java.math.*;
import java.util.*;
import java.io.*;
public class c
{
    static Random rnd = new Random();
    public static String addDigits(String a, int n)
    {
        if(a==null) return null;
        if(n<=0) return a;
        for(int i=0; i<n; i++)
            a+=rnd.nextInt(10);
        return a;
    }
    public static void main(String[] args) throws IOException
    {
        int n = 10000; \\number of iterations
        int k = 10;    \\number of digits added at each iteration
        BigInteger a;
        BigInteger b;
        String as = "";
        String bs = "";
        as += rnd.nextInt(9)+1;
        bs += rnd.nextInt(9)+1;
        a = new BigInteger(as);
        b = new BigInteger(bs);
        FileWriter fw = new FileWriter("c.txt");
        long t1 = System.nanoTime();
        a.multiply(b);
        long t2 = System.nanoTime();
        //fw.write("1,"+(t2-t1)+"\n");
        if(k>0) {
            as = addDigits(as, k-1);
            bs = addDigits(as, k-1);
        }
        for(int i=0; i<n; i++)
        {
            a = new BigInteger(as);
            b = new BigInteger(bs);
            t1 = System.nanoTime();
            a.multiply(b);
            t2 = System.nanoTime();
            fw.write(((i+1)*k)+","+(t2-t1)+"\n");
            if(i < n-1)
            {
                as = addDigits(as, k);
                bs = addDigits(as, k);
            }
            System.out.println((i+1)*k);
        }       
        fw.close();
    }
}
它测量n位大整数的乘法时间
结果:
你可以很容易地看到趋势,但为什么在50000位以上有这么大的噪音?这是因为垃圾回收器还是其他因素会影响我的结果?执行测试时,没有其他应用程序正在运行。
测试结果只有奇数位数。测试时间较短(n=1000,k=100)

奇数位数 (n=10000, k=10)
如您所见,65000至70000之间有巨大的噪音。我想知道为什么...
奇数位 (n=10000, k=10),每 1000 次 迭代一次 导致噪声介于 50000-70000 之间
迭代一次 导致噪声介于 50000-70000 之间System.gc()
 
					 
				 
				    		 
				    		 
				    		