【问题标题】:Automatically profiling at the method level in .NET with Stopwatch使用 Stopwatch 在 .NET 中的方法级别自动分析
【发布时间】:2017-11-29 08:59:34
【问题描述】:

有没有一种方法可以清晰、轻松地分析方法/函数,而无需每次都对每个方法都进行此操作?

  1. 声明一个秒表变量:Dim stopwatch As Stopwatch = Stopwatch.StartNew()
  2. 最后调用stopwatch.Stop()
  3. stopwatch.Elapsed.TotalMilliseconds 结尾输出结果

并不是说这很麻烦,但是在许多函数上重复它会有点弄脏代码,我想知道是否有一种方法可以在一个干净的步骤中做到这一点,即在方法开始时开始计算时间并且自动检测何时停止。我对此表示怀疑,但我不是专家。

谢谢。

【问题讨论】:

    标签: .net profiling


    【解决方案1】:

    为什么不编写自己的辅助方法?像这样:

    public class TimerLogger : IDisposable
    {
        private string _message;
        private Stopwatch _timer;
    
        public TimerLogger(string message)
        {
            _message = message;
            _timer = new Stopwatch();
            _timer.Start();
        }
    
        public void Dispose()
        {
            _timer.Stop();
            Console.WriteLine($"Calculation time for {_message}: {_timer.ElapsedMilliseconds}");        
        }
    }
    

    用法:

    using(new TimerLogger("Test")){
        for(int i = 0; i < 1000; i++)
            Thread.Sleep(5);
    }
    

    【讨论】:

    • 这太棒了!几乎正是我正在寻找的东西。谢谢。
    【解决方案2】:

    Roman 的响应正是我想要的,但它是 C#。以防万一有人需要像我一样在 VB.NET 中执行此操作,方法如下。它还输出有关调用助手的方法和特定行的详细信息。

    Public Class Profiler
    
        Implements IDisposable
    
        Private ReadOnly _timer As Stopwatch
    
        Private ReadOnly _methodName As String
        Private ReadOnly _lineNumber As Integer
    
        Public Sub New(<System.Runtime.CompilerServices.CallerMemberName> Optional memberName As String = Nothing,
                       <System.Runtime.CompilerServices.CallerLineNumber()> Optional sourceLineNumber As Integer = 0)
    
            _timer = New Stopwatch()
            _methodName = memberName
            _lineNumber = sourceLineNumber
            _timer.Start()
    
        End Sub
    
        Public Sub Dispose() Implements System.IDisposable.Dispose
    
            _timer.Stop()
    
            Console.WriteLine("A timer was called in the method " & _methodName & ", line " & _lineNumber & "; the result was " & _timer.Elapsed.Milliseconds & "ms." );
    
        End Sub
    
    End Class
    

    祝你有美好的一天。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2018-05-20
      • 1970-01-01
      相关资源
      最近更新 更多