TimeTracker: a C# class to measure source code execution time

TimeTracker: una classe C# per misurare il tempo di esecuzione del codice

Among the most common - and important - needs during software development certainly is carrying out each task while achieving the best possible performance. In order to do this is essential to adopt a proper tool that will allow us to measure the execution time of each method, function or code block in a suitable time unit (be it milliseconds, microseconds or nanoseconds) with a decent amount of accuracy.

Ideally, such tool should also let the developer execute several measurements within the same execution context, allowing him to set multiple time laps and giving the chance to compare them with each other: to cut things short, we are talking about something that provides the core functionality of a common stopwatch.

With this goal in mind, a few years ago I developed a simple C# class that basically puts this concept into life. Its name is TimeTracker and it can be used to set multiple time laps during the execution of any program: each one of them, once created, can be compared with any other lap to calculate the time lapse between them using one the available time formats: nanoseconds, microseconds, milliseconds, seconds, minutes or hours.

This is a basic usage example:

The sample is taken from a standard ASP.NET MVC application, yet the class can be effectively used within any other possible C# context: ASP.NET MVC, Windows Forms, WFC, ASP.NET Core and the likes. It's also entirely possible to run global-scope measurements: we just need to instantiate a single TimeTracker object globally - for example in the Startup class of a standard ASP.NET 4 / ASP.NET Core project - and add multiple time laps from different points and / or along the entire application life cycle.

This is the class full source code:

The code itself is quite documented and filled with comments, so it should need no further explanations. Despite being written several years ago, the class can still prove its usefulness to properly analyze the performances of almost any kind of C# source code block in a rather accurate way.

That's it for now: happy Time Tracking!

About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.

View all posts by Ryan

Leave a Reply

Your email address will not be published. Required fields are marked *

The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.