flatterino
flatterino

Reputation: 1025

Automatically profiling at the method level in .NET with Stopwatch

Is there a way of cleanly, easily profiling a method/function that doesn't involve going through this every time, for every method?

  1. Declaring a Stopwatch variable: Dim stopwatch As Stopwatch = Stopwatch.StartNew()
  2. Calling stopwatch.Stop() at the end
  3. Outputting the results with stopwatch.Elapsed.TotalMilliseconds at he end

Not that it's a big hassle, but repeating it over many functions dirties up the code somewhat, and I was wondering if there might be a way of doing this in one clean step that starts counting time at the start of a method and automatically detects when to stop. I doubt it, but I'm no expert.

Thanks.

Upvotes: 0

Views: 129

Answers (2)

flatterino
flatterino

Reputation: 1025

Roman's response is exactly what I was looking for, but it's C#. Just in case anyone needs to do it in VB.NET like me, here's how. It also outputs details about the method in which the helper was called and the specific line, too.

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

Have a nice day.

Upvotes: 1

Roman Koliada
Roman Koliada

Reputation: 5112

Why not write your own helper method? Like this:

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

Usage:

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

Upvotes: 1

Related Questions