使用秒表在.NET中自动分析方法级别

时间:2017-11-29 08:59:34

标签: .net profiling

对于每种方法,有没有一种干净利落的方法,可以轻松地分析每次都不涉及这种方法/功能的方法/功能?

  1. 声明一个秒表变量:Dim stopwatch As Stopwatch = Stopwatch.StartNew()
  2. 最后致电stopwatch.Stop()
  3. 使用stopwatch.Elapsed.TotalMilliseconds输出结果
  4. 并不是说这是一个很大的麻烦,但是在许多函数上重复它会使代码有点污染,我想知道是否有一种方法可以在一个干净的步骤中执行此操作,该方法在方法开始时开始计算时间并且自动检测何时停止。我对此表示怀疑,但我不是专家。

    感谢。

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:1)

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

度过愉快的一天。

相关问题