这个小型控制台应用程序计算一个 BigInteger 并给我一个反馈它击中的指数。
现在我对一些速度改进感到好奇。我能做些什么?
谢谢你的建议!
using System;
using System.Collections.Generic;
using System.Numerics;
namespace Counter
{
internal class Program
{
private static readonly Dictionary<BigInteger, int> Dic = new Dictionary<BigInteger, int>();
private static void Main(string[] args)
{
Console.WriteLine("Start with counting ... from 1 to 2^256.");
Console.WriteLine();
CreateDict();
var bigInteger = new BigInteger();
Console.WriteLine("D:HH:mm:ss,ms - fac. - Number");
Console.WriteLine("---------------------------------------------------");
var startTime = DateTime.UtcNow;
while (true)
{
bigInteger++;
if (Dic.ContainsKey(bigInteger))
{
Console.WriteLine("{0:G} - 2^{1,3} = {2:#,0}", (DateTime.UtcNow - startTime), Dic[bigInteger], bigInteger);
}
}
}
private static void CreateDict()
{
for (int i = 1; i <= 256; i++)
{
Dic.Add(BigInteger.Pow(2, i), i);
}
}
}
}
输出: http: //pastebin.com/bMBntFsL
进步
使用 BigInteger 并不是那么好。
大整数 2^26 = 5s
双 2^26 = 1,3s
从 Dict 切换到直接比较要快得多
int i = 1;
double pow = Math.Pow(2, i);
while (true)
{
bigInteger++;
if (bigInteger == pow)
{
Console.WriteLine("{0:G} - 2^{1,3} = {2:#,0}", (DateTime.UtcNow - startTime), Dic[bigInteger], bigInteger);
i++;
pow = Math.Pow(2, i);
}
}
字典 2^26 = 1,3s
"<" 2^26 = 0,5s