如何对 LINQPad 查询进行性能分析?

3

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

请注意,我并不是在问如何分析LINQ查询;而是普通的(C#)代码在LINQPad“查询”文件中的优化位置(一个常规的LINQPad文件)。

1个回答

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");
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接