我写了一个小程序来比较我的笔记本电脑的性能。为了使程序占用大量 CPU,我使用一些多线程代码(通过 Parallel API 实现)实现了 Rabin-Karp 模式匹配算法。
我注意到,当程序在编译器优化标志关闭的情况下执行时,它所花费的时间比在优化标志打开的情况下执行所需的时间要多得多。
例如:
- 所用时间(优化标志关闭时):40 秒(大约)
- 所用时间(优化标志打开时):18 秒(大约)
我很想知道编译器正在应用什么样的优化来增加性能的显着提高。任何关于如何理解在打开/关闭此标志的情况下执行代码时发生了什么的指针都会非常有帮助。
代码
void Main()
{
Dictionary<string,bool> collection = new Dictionary<string,bool>();
IEnumerable<string> commonWords = File.ReadAllLines(@"G:\LINQPad4\words.txt")
.Where(x => !string.IsNullOrEmpty(x)).Select(t => t.Trim());
string magna_carta = File.ReadAllText(@"G:\LINQPad4\magna-carta.txt");
Parallel.ForEach(commonWords,
() => new Dictionary<string,bool>(),
(word, loopState, localState) =>
{
RabinKarpAlgo rbAlgo = new RabinKarpAlgo(magna_carta,word);
localState.Add(word,rbAlgo.Match());
return localState;
},
(localState) =>
{
lock(collection){
foreach(var item in localState)
{
collection.Add(item.Key, item.Value);
}
}
});
collection.Dump();
}
public class RabinKarpAlgo
{
private readonly string inputString;
private readonly string pattern;
private ulong siga = 0;
private ulong sigb = 0;
private readonly ulong Q = 100007;
private readonly ulong D = 256;
public RabinKarpAlgo(string inputString, string pattern)
{
this.inputString = inputString;
this.pattern = pattern;
}
public bool Match()
{
for (int i = 0; i < pattern.Length; i++)
{
siga = (siga * D + (ulong)inputString[i]) % Q;
sigb = (sigb * D + (ulong)pattern[i]) % Q;
}
if(siga == sigb)
return true;
ulong pow = 1;
for (int k = 1; k <= pattern.Length - 1; k++)
pow = (pow * D) % Q;
for (int j = 1; j <= inputString.Length - pattern.Length; j++)
{
siga = (siga + Q - pow * (ulong)inputString[j - 1] %Q) % Q;
siga = (siga * D + (ulong)inputString[j + pattern.Length - 1]) % Q;
if (siga == sigb)
{
if (inputString.Substring(j, pattern.Length) == pattern)
{
return true;
}
}
}
return false;
}
}
您可以从以下 gitHub 存储库下载相关文件:Rabin-Karp 测试
文章:性能测试