当我注意到算法中的一个有趣问题时,我一直在调查我们开发站点上的事件查看器应用程序的一些性能问题。然后我创建了一个简化的测试项目来测试两种不同的算法。该程序基本上使用该类检索 Windows 事件日志EventLog
,然后将这些日志转换为可查询的EventLogItem
实体。
该操作使用两个不同的循环来执行和计时。第一个(向后)循环从列表中最后一项的索引开始,翻译该项,然后减少索引。该方法定义如下:
private static void TranslateLogsUsingBackwardLoop()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
var originalLogs = EventLog.GetEventLogs();
var translatedLogs = new List<EventLogItem>();
Parallel.ForEach<EventLog>(originalLogs, currentLog =>
{
for (int index = currentLog.Entries.Count - 1; index >= 0; index--)
{
var currentEntry = currentLog.Entries[index];
EventLogItem translatedEntry = new EventLogItem
{
MachineName = currentEntry.MachineName,
LogName = currentLog.LogDisplayName,
CreatedTime = currentEntry.TimeGenerated,
Source = currentEntry.Source,
Message = currentEntry.Message,
Number = currentEntry.Index,
Category = currentEntry.Category,
Type = currentEntry.EntryType,
InstanceID = currentEntry.InstanceId,
User = currentEntry.UserName,
};
lock (translatedLogs)
{
translatedLogs.Add(translatedEntry);
}
}
});
stopwatch.Stop();
Console.WriteLine("{0} logs were translated in {1} using backward loop.", translatedLogs.Count, stopwatch.Elapsed);
}
第二个(前向)循环从索引 0 开始并递增索引。该方法定义如下:
private static void TranslateLogsUsingForwardLoop()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
var originalLogs = EventLog.GetEventLogs();
var translatedLogs = new List<EventLogItem>();
Parallel.ForEach<EventLog>(originalLogs, currentLog =>
{
for (int index = 0; index < currentLog.Entries.Count; index++)
{
var currentEntry = currentLog.Entries[index];
EventLogItem translatedEntry = new EventLogItem
{
MachineName = currentEntry.MachineName,
LogName = currentLog.LogDisplayName,
CreatedTime = currentEntry.TimeGenerated,
Source = currentEntry.Source,
Message = currentEntry.Message,
Number = currentEntry.Index,
Category = currentEntry.Category,
Type = currentEntry.EntryType,
InstanceID = currentEntry.InstanceId,
User = currentEntry.UserName,
};
lock (translatedLogs)
{
translatedLogs.Add(translatedEntry);
}
}
});
stopwatch.Stop();
Console.WriteLine("{0} logs were translated in {1} using forward loop.", translatedLogs.Count, stopwatch.Elapsed);
}
主要方法:
static void Main(string[] args)
{
TranslateLogsUsingForwardLoop();
Console.WriteLine();
Thread.Sleep(2000);
TranslateLogsUsingBackwardLoop();
Console.ReadLine();
}
这是我得到的(多次执行此测试,结果几乎相同):
请注意,我测试的服务器每秒都会记录到事件日志,这就是翻译日志的数量不同的原因。那么为什么反向循环更快呢?我最初认为这是因为在后向循环算法中,currentLog.Entries.Count
只评估一次,而在前向循环中,它需要index
在每次循环迭代时计算和比较,但话又说回来,这似乎不对。有任何想法吗?