如何配置LINQPad查询?

时间:2018-05-02 20:37:48

标签: profiling linqpad

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

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

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法是编写一个Visual Studio控制台应用程序。除此之外,我使用了我添加到My Extensions中的一个类 - 它不是非常准确,因为它不能很好地解释它自己的开销,而是通过帮助多个循环:

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