Click here to Skip to main content
15,886,067 members
Articles / Programming Languages / C#
Tip/Trick

Simple Way to Measure Execution Time by Stopwatch

Rate me:
Please Sign up or sign in to vote.
4.64/5 (13 votes)
23 Sep 2020CPOL2 min read 20.1K   13   16
Easy way to measure execution time of the code block

Introduction

There are plenty of articles on how to measure execution time by stopwatch. Most of them are very complex. I will try to introduce my way to do it. I think that it will be the shortest one because like all programmers, I am lazy. ;)

I was frustrated when I tried to measure execution time of some functions. Problem was that every time I did try to do it, it was always the same code and it was always copy and paste. It's fine until you look at your code and on one page, you can see plenty of this:

C#
stopwatch.Start();
SpecialFunctionToMeasure();
stopwatch.Stop()

And the problem was if your function triggers an exception which you didn't expect - like always when you think that everything is ok. :) If this happens, you will try to make code like this:

C#
stopwatch.Start();
try
{
    SpecialFunctionToMeasure();
}
catch(....)
{
    ....
}
finally
{
    stopwatch.Stop();
}

It looks horrible. :) Isn't it ?

Solution

To understand my way of measuring time of execution, you have to have basic knowledge about C#, but I will try to explain in an easy way those few lines of code. My code for the class is as given below:

C#
public class TimeMeasurementBlock : IDisposable
{
    public Stopwatch Stopwatch { get; private set; }

    public TimeMeasurementBlock(Stopwatch stopwatch)
    {
        Stopwatch = stopwatch;
        if (Stopwatch != null)
            Stopwatch.Start();
    }

    #region Implementation of IDisposable

    public void Dispose()
    {
        if (Stopwatch != null)
            Stopwatch.Stop();
    }

    #endregion
}

As you can see, the code is simple and should not disturb measurements. Of course, every additional code will disturb measurements, but I hope we are not making code for HFT. :)

You can skip public property if you wish. I put it because I am using it inside my code and it looks nice. :) Also, you can skip part with checking if Stopwatch is null if you are sure of what you are doing and to save few ticks. :)

Updated code to use new functionality of the C#:

C#
public class TimeMeasurementBlock : IDisposable
{
    public Stopwatch Stopwatch { get; private set; }

    public TimeMeasurementBlock(Stopwatch stopwatch)
    {
        Stopwatch = stopwatch;
        Stopwatch?.Start();
    }


    #region Implementation of IDisposable

    public void Dispose()
    {
        Stopwatch?.Stop();
    }

    #endregion
}

Using the Code

It is very simple to use this class in your code. The code below should put light in this dark region... :)

C#
Stopwatch stopwatch = new Stopwatch();
using (var timeBlock = new TimeMeasurementBlock(stopwatch))
{
...
}

...or if you don't need to access class inside block:

C#
Stopwatch stopwatch = new Stopwatch();
using (new TimeMeasurementBlock(stopwatch))
{
...
}

As you probably know, "using" guarantees you that will call Dispose function at the end of the block even if will be exception inside. I think that this is the simplest solution for measuring execution time. Life is already very complicated so we don't have to complicate our source code. :)

License

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


Written By
Netherlands Netherlands
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionImplementation of IDisposable Pin
samsong15-Nov-20 6:34
samsong15-Nov-20 6:34 
SuggestionWhy not please everybody Pin
HenkAlles1-Oct-20 10:01
HenkAlles1-Oct-20 10:01 
GeneralRe: Why not please everybody Pin
TymekMM7-Oct-20 10:13
TymekMM7-Oct-20 10:13 
GeneralRe: Why not please everybody Pin
HenkAlles7-Oct-20 10:27
HenkAlles7-Oct-20 10:27 
GeneralRe: Why not please everybody Pin
TymekMM7-Oct-20 10:36
TymekMM7-Oct-20 10:36 
QuestionWouldn't this be better? Pin
Jfarr23-Sep-20 3:05
Jfarr23-Sep-20 3:05 
AnswerRe: Wouldn't this be better? Pin
Member 1015788723-Sep-20 20:13
Member 1015788723-Sep-20 20:13 
GeneralRe: Wouldn't this be better? Pin
TymekMM24-Sep-20 19:42
TymekMM24-Sep-20 19:42 
QuestionWhy the need to pass the StopWatch? Pin
PedroPortilha22-Jun-15 7:16
PedroPortilha22-Jun-15 7:16 
AnswerRe: Why the need to pass the StopWatch? Pin
TymekMM22-Jun-15 7:31
TymekMM22-Jun-15 7:31 
GeneralRe: Why the need to pass the StopWatch? Pin
LoveJenny22-Jun-15 23:01
LoveJenny22-Jun-15 23:01 
TimeMeasurementBlock should not contain the Stopwatch instance, It should contain a DataTime object.
GeneralRe: Why the need to pass the StopWatch? Pin
TymekMM22-Jun-15 23:22
TymekMM22-Jun-15 23:22 
GeneralRe: Why the need to pass the StopWatch? Pin
Sacha Barber24-Sep-20 0:23
Sacha Barber24-Sep-20 0:23 
GeneralRe: Why the need to pass the StopWatch? Pin
Jaxag23-Jun-15 2:59
Jaxag23-Jun-15 2:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.