我寫了一個代碼,用於計算二進制文件中的每個字節頻率。使用Linq。執行Linq表達式時,代碼似乎很慢。在這種邏輯上似乎很難實現並行性。要建立頻率超過475MB的頻率表,大約需要1分鐘。Linq優化計數和組
class Program
{
static void Main(string[] args)
{
Dictionary<byte, int> freq = new Dictionary<byte, int>();
Stopwatch sw = new Stopwatch();
sw.Start();
//File Size 478.668 KB
byte[] ltext = File.ReadAllBytes(@"D:\Setup.exe");
sw.Stop();
Console.WriteLine("Reading File {0}", GetTime(sw));
sw.Start();
Dictionary<byte, int> result = (from i in ltext
group i by i into g
orderby g.Count() descending
select new { Key = g.Key, Freq = g.Count() })
.ToDictionary(x => x.Key, x => x.Freq);
sw.Stop();
Console.WriteLine("Generating Freq Table {0}", GetTime(sw));
foreach (var i in result)
{
Console.WriteLine(i);
}
Console.WriteLine(result.Count);
Console.ReadLine();
}
static string GetTime(Stopwatch sw)
{
TimeSpan ts = sw.Elapsed;
string elapsedTime = String.Format("{0} min {1} sec {2} ms",ts.Minutes, ts.Seconds, ts.Milliseconds);
return elapsedTime;
}
我試過使用幾個循環來實現非linq解決方案,其性能大致相同。請任何建議來優化這個。對不起,我的英語不好
「我已經寫了一個代碼來計算二進制文件中的每個字節頻率。使用Linq」這是...「令人欽佩」。 – 2010-10-24 20:33:44
@Kirk:爲什麼,你的反對意見是? – 2010-10-24 20:36:01