Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Capture Code Snippet Execution Time

5.00/5 (1 vote)
7 Oct 2024CPOL 1.6K   34  
Log the duration a snippet of code takes, with this NuGet package called SnippetDurationLogger
Be able to log the duration a snippet of code takes to execute, log it using your existing logger. Not like Benchmarking, which times the whole method, but if you just want to time a snippet of your code within your method. Plus, you can log multiple snippets within the same method.

Download SnippetDurationLogger.zip

NuGet Package Reference

Introduction

I'm sure like me, in numerous projects you've had to capture and investigate long running processes. Where you had to find the snippet of code that was causing the issue and then drilling down to see what lines where causing the latency.

You would have numerous logging statements salt and peppered throughout your code (often leaving them in by mistake!!!)

Background

This NuGet Package I created, has been developed for scenarios where a developer wishes to capture the execution time of a snippet of code. Not the execution time for a full method, but a snippet of code in the method and then log it.

Using the code

Add the following NuGet package to your project - SnippetDurationLogger

Image 1

Add this namespace to your class:

C#
using SnippetDuration.Classes;

Then, around the snippet of code you wish to get the execution time against, apply the  Logger extension method LogExecutionTime:

C#
_logger.LogExecutionTime("Add simple comment...", () =>
{
     // Your existing code block, whose execution time will be logged        
});

In your comment, you can add string interpolation variables: 

C#
_logger.LogExecutionTime($"Fnx parameter - {myParam}", () => 
{ 
      // Your existing code block, whose execution time will be logged 
});

Then in your log file you will see the comment (and the interpolation values if included) along with the execution time:

Image 2

Below is a complete example:

C#
using Microsoft.Extensions.Logging;
using SnippetDuration.Classes;

namespace SnippetDurationLoggerConsole
{
    internal class ExternalMethods
    {
        private readonly ILogger<ExternalMethods> _logger;
        public ExternalMethods(ILogger<ExternalMethods> logger)
        {
            _logger = logger; // injected logger
        }

        public void LongRunningprocess()
        {
           _logger.LogExecutionTime("Testing DB Call", () =>              
            {
                // Code block whose execution time will be logged
                System.Threading.Thread.Sleep(3500); // Simulate a long running process
            });
        }
    }
}

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)