经常如此,我发现自己对小块代码进行基准测试,以确定哪种实现最快.
我经常看到一些 comments ,说基准测试代码没有考虑jitting或垃圾收集器.
我有以下简单的基准测试功能,我已经慢慢发展:
static void Profile(string description, int iterations, Action func) {
// warm up
func();
// clean up
GC.Collect();
var watch = new Stopwatch();
watch.Start();
for (int i = 0; i < iterations; i++) {
func();
}
watch.Stop();
Console.Write(description);
Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds);
}
用法:
Profile("a descriptions", how_many_iterations_to_run, () =>
{
// ... code being profiled
});
这个实现有什么缺陷吗?它是否足以证明实现X比实现Y在Z迭代中更快?你能想出什么办法来改善这一点吗?
EDIT个 很明显,基于时间的方法(相对于迭代)是首选的,有没有人有时间判断不会影响性能的实现呢?