Location>code7788 >text

C# Development Tips Easily Monitor Method Execution Time Consumption

Popularity:167 ℃/2024-07-23 10:36:07

preamble

is a powerful library for measuring the execution time of methods in .NET applications. Allows you to automatically measure and record the execution time of methods without modifying the code.

This tool is based on .NET's weaving technique, which inserts timing logic by modifying IL (Intermediate Language) code to record timestamps before and after a method call, thus calculating the execution time of the method.

It can be seamlessly integrated into projects using the Fody plugin framework, so adding performance measurement capabilities to your code is easy.

Usage

1. Install the NuGet package

In Visual Studio, open the NuGet Package Manager, search for and install theOr use the command method

PM> Install-Package Fody
PM> Install-Package 

The specific operation is shown in the following figure:

2、Use the Time feature

using MethodTimer;

namespace DemoConsole
{
    internal class Program
    {
        /// <summary>
        /// program entry
/// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // Calling Sample Methods
            new Program().DoSomething();

            ("End of test method execution!!!");

            ();
        }

        /// <summary>
        /// sample method
/// </summary>
        [Time]
        public void DoSomething()
        {
            ("Test method execution time!!!");
        }
    }
}

NET weaving framework, you need to make sure that Fody is enabled in your project and that you have added the following to the "Fody" tab of your project propertiesMethodTimerModule.

3. Implementation effects

Start running the program and you can view the execution time consumed by the method in the output window as shown below:

4. Other notes

The Time feature can be added not only to methods but also to Classes, as shown in the following code:

using MethodTimer;

namespace ConsoleApp3
{
    [Time]
    internal class Program
    {
        /// <summary>
        /// program entry
/// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // Calling Sample Methods
            new Program().DoSomething();

            new Program().ToDoSomething();

            ("End of method execution!!!");

            ();
        }

        /// <summary>
        /// Example Method 1
/// </summary>
      
        public void DoSomething()
        {
            ("001 - Test the execution time method!!!!");
           
        }
        /// <summary>
        /// Example Method 2
/// </summary>

        public void ToDoSomething()
        {
            ("002 - Test the execution time method!!!!");

        }
    }
}

After running the program, you can output the execution time of each method in the class.

In fact, when the Time feature is added to the code, Fody automatically generates the following code

 public class MyClass
 {
        [Time]
        public void DoSomething()
        {
            Stopwatch stopwatch = new Stopwatch();
            ();

            // primitive methodology
            (1000); // simulation work

            ();

            // Output or record execution time
            ($"Execution time: {} ms");
        }
 }

5. Interception records

If you want to manually process the log records, you can define a static class to intercept the log records, the method of the example, the specific code shown below

public static class MethodTimeLogger
{
    public static void Log(MethodBase methodBase, TimeSpan elapsed, string message)
    {
        //Do some logging here
    }
}

Generated code

public class MyClass
{
    public void MyMethod()
    {
        var stopwatch = ();
        try
        {
            ("Hello");
        }
        finally
        {
            ();
            (methodof(), );
        }
    }
}

is a very useful tool, especially in the performance tuning phase, to help you quickly identify which methods are performance bottlenecks so that you can target them for optimization.

Main features

1. Non-intrusive

Instead of adding additional timing code to the source code, you just need to add the appropriate NuGet package to the project and do some configuration in the project properties to automatically add timing to the methods.

2. Flexible configuration

You can selectively time certain methods or exclude methods that you don't want to be timed. This is usually configured through the characteristics of the method or the namespace of the class.

3. Diversification of output results

Timing results can be output to different places, such as the console, log files, or via event tracing (ETW), depending on your configuration.

4. Low performance impact

Although timing logic is inserted into the method, it is designed to have the least possible impact on performance, which is achieved through a carefully optimized IL code insertion strategy.

summarize

is a powerful tool that provides an easy way to monitor the execution time of C# methods, especially for situations where you need to quickly diagnose performance problems.

Through its flexible configuration and non-intrusive nature, it fits seamlessly into the existing development process and helps our team improve the performance and responsiveness of our applications.

This tool is particularly well suited for quickly identifying performance bottlenecks during the development and testing phases without having to explicitly add timing code to the code, which can keep the source code neat and maintainable.

open source address

/Fody/MethodTimer

 

If you find this article useful, welcome to join WeChat [DotNet technician] community to share ideas and grow with other tech-loving peers.