【问题标题】:How to profile a LINQPad query?如何分析 LINQPad 查询?
【发布时间】:2018-05-02 20:37:47
【问题描述】:

我想确定在 LINQPad 查询中优化代码的位置。我该怎么做?

请注意,我不是询问如何分析 LINQ 查询;只是 LINQPad“查询”文件(常规 LINQPad 文件)中的常规 (C#) 代码。

【问题讨论】:

    标签: profiling linqpad


    【解决方案1】:

    我认为最简单的方法是编写一个 Visual Studio 控制台应用程序。除此之外,我使用了我添加到我的扩展中的一个类——它并不是非常准确,因为它没有很好地考虑到它自己的开销,而是通过帮助进行了多个循环:

    using System.Runtime.CompilerServices;
    
    public static class Profiler {
        static int depth = 0;
        static Dictionary<string, Stopwatch> SWs = new Dictionary<string, Stopwatch>();
        static Dictionary<string, int> depths = new Dictionary<string, int>();
        static Stack<string> names = new Stack<string>();
        static List<string> nameOrder = new List<string>();
    
        static Profiler() {
            Init();
        }
    
        public static void Init() {
            SWs.Clear();
            names.Clear();
            nameOrder.Clear();
            depth = 0;
        }
    
        public static void Begin(string name = "",
            [CallerMemberName] string memberName = "",
            [CallerFilePath] string sourceFilePath = "",
            [CallerLineNumber] int sourceLineNumber = 0) {
            name += $" ({Path.GetFileName(sourceFilePath)}: {memberName}@{sourceLineNumber})";
    
            names.Push(name);
            if (!SWs.ContainsKey(name)) {
                SWs[name] = new Stopwatch();
                depths[name] = depth;
                nameOrder.Add(name);
            }
            SWs[name].Start();
            ++depth;
        }
    
        public static void End() {
            var name = names.Pop();
            SWs[name].Stop();
            --depth;
        }
    
        public static void EndBegin(string name = "",
            [CallerMemberName] string memberName = "",
            [CallerFilePath] string sourceFilePath = "",
            [CallerLineNumber] int sourceLineNumber = 0) {
            End();
            Begin(name, memberName, sourceFilePath, sourceLineNumber);
        }
    
        public static void Dump() {
            nameOrder.Select((name, i) => new {
                Key = (new String('\t', depths[name])) + name,
                Value = SWs[name].Elapsed
            }).Dump("Profile");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 2010-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多