使用 Stopwatch 在 .NET 中的方法级别自动分析

Automatically profiling at the method level in .NET with Stopwatch

有没有一种方法可以干净、轻松地对 method/function 进行分析,而无需每次都对每种方法进行分析?

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

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

谢谢。

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

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

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

祝你有愉快的一天。