【问题标题】:Best way to time events in Visual Studio? [closed]在 Visual Studio 中计时事件的最佳方式是什么? [关闭]
【发布时间】:2021-04-21 16:26:40
【问题描述】:

在 Visual Studio 中,我一直想知道执行代码需要多长时间。通常我会这样做:

var timer = new Stopwatch();

// run some code 

timer.Start();
timer.Stop();

是否可以像 Visual Studio 中的断点一样执行此操作?我知道这可能是不可能的,因为有多个线程,但它甚至会充当两个额外的断点作为计时器启动/停止在 vs 或扩展中会很酷。 这存在吗?

【问题讨论】:

标签: c# visual-studio performance debugging


【解决方案1】:

Diagnostics Tools - Events 让您查看每段代码的运行时间:

【讨论】:

    【解决方案2】:

    使用断点的替代方法是编写静态计时器方法并将其输出到您选择的记录器?

    我为我的一个输出到 Serilog 的项目想出了以下内容。但是如果你没有记录器,你可以将它调整为 Console.WriteLine()。

        public static Task LogExecutionTime(string? detail, Action action)
        {
            if (!Log.IsEnabled(Serilog.Events.LogEventLevel.Debug))
            {
                action.Invoke();
                return Task.CompletedTask;
            }
            var stackTrace = new StackTrace();
            var methodName = stackTrace.GetFrame(1).GetMethod().Name;
    
            var watch = Stopwatch.StartNew();
            action.Invoke();
            watch.Stop();
    
            var detailStr = detail is null ? string.Empty : "." + detail;
            Log.Logger.Debug($"{methodName}{detailStr}: {watch.ElapsedMilliseconds}ms");
    
            return Task.CompletedTask;
        }
    

    示例用法

     LogExecutionTime("Detail", () =>
     {
              // your code here
     }
    

    修改为更通用的实现

    public static Task LogExecutionTime(Action action)
    {
        var stackTrace = new StackTrace();
        var methodName = stackTrace.GetFrame(1).GetMethod().Name;
    
        var watch = Stopwatch.StartNew();
        action.Invoke();
        watch.Stop();
    
        Console.WriteLine($"[{DateTime.Now}] {methodName}: {watch.ElapsedMilliseconds}ms");
    
        return Task.CompletedTask;
    }
    

    示例用法

     LogExecutionTime(() =>
     {
              // your code here
     }
    

    【讨论】: