相关疑难解决方法(0)

在C#中对小代码示例进行基准测试,是否可以改进此实现?

经常这样我发现自己对小块代码进行基准测试,看看哪个实现最快.

我经常看到基准测试代码没有考虑到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);
    }
Run Code Online (Sandbox Code Playgroud)

用法:

Profile("a descriptions", how_many_iterations_to_run, () =>
{
   // ... code being profiled
});
Run Code Online (Sandbox Code Playgroud)

这个实现是否有任何缺陷?是否足以表明实现X比Z迭代实现Y更快?您能想出任何可以改善这种情况的方法吗?

编辑 很明显,基于时间的方法(与迭代相反)是首选,是否有人有任何实施时间检查不会影响性能?

.net c# performance profiling

104
推荐指数
6
解决办法
2万
查看次数

标签 统计

.net ×1

c# ×1

performance ×1

profiling ×1