在 SO 上,我经常会对小代码块进行基准测试,以确定哪个实现方式最快。
经常会看到评论说基准测试代码没有考虑到即时编译器和垃圾回收器。
我有以下简单的基准测试函数,并且已经逐步完善:
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在Z次迭代中比实现Y更快吗?您能想到任何改进的方法吗?
编辑 很明显,基于时间的方法(而不是迭代次数)更受欢迎,有人有任何实现,其中时间检查不会影响性能吗?