Adding Stopwatch to all functions of C# project

Viewed 57

I have a C# project that uses a lot of functions. I want to make a simple test with stopwatch. But I don't want to add stopwatch to every function one by one.

I am looking for a way to add stopwatch to each function.

I don't have to use stopwatch, even simple timer would do the job. I just need to know how to add stopwatch, timer etc to each function without repeating same process.

Thanks for help.

2 Answers

Don't. Use a profiler instead.

Stopwatches are great if you want to investigate the runtime of some specific operation that you are curious about. But using one for every function is misguided, consider that functions can be very small, and stopwatches have some overhead.

If you want to monitor the overall performance of your program a performance profiler is the correct tool to use. Some profilers offer multiple different measurement modes, and some offer an instrumented mode that give an accurate count of how often a method is called. But the overhead of this is so high that it is only really usable to analyze specific test-cases.

The visual studio debugger should also be able to show the elapsed time between two breakpoints, these times may not be accurate due to lack of optimization, but should give some indication of the time spent.

There is a Fody weaver called MethodTimer that you can use in your test projects to log method execution time without impacting your production code. You need to add both the Fody and MethodTimer.Fody nuget packages to your project:

Fody Nuget

MethodTimer.Fody Nuget

Working Example Project

Example


public class MyApplicationClass
{   
    public static void TimeExecution()
    {
        await Task.Delay(1000);
    }
}

public class MyTestClass
{ 
    [Test]
    [Time]
    public async Task TimedExecution_Test()
    {
        MyApplicationClass.TimeExecution();
    }
}
//Optional interceptor to customize logging output of MethodTimer.Fody
public static class MethodTimeLogger
{
    public static void Log(MethodBase methodBase, long milliseconds, string message)
    {
        //Write to VS Debug Output window, logger, etc...
        Debug.WriteLine($"Time Ms: {milliseconds}");
    }
}

Related