DEV Community

Cover image for The efficient way to measure time in .NET
Francis Adediran
Francis Adediran

Posted on

1

The efficient way to measure time in .NET

One of my new year resolution for 2025 is to share my coding and engineering challenges, learnings and musings.

Today, i'll like to share a technique that i recently discovered whilst trying to measure how long it takes to execute a method or function in .NET. I faced this challenge when working with the vector search component of Weaviate. Weaviate is open-source vector database state-of-the-art machine learning (ML) models to turn your data - text, images, and more - into a searchable vector database. It stores both objects and vectors, allowing for the combination of vector search with structured filtering. Thus, the performance of search is integral especially for a database.

Now, there are many ways to measure time in .NET. The common way these days is using Stopwatch class like this:

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// Your code: Doing something e.g Thread.Sleep(3000);
stopwatch.Stop();
TimeSpan elapsedTime = stopwatch.Elapsed;

However, i found the Stopwatch object creation and memory allocation time consuming in our app. I tried to factor the memory/time used by Stopwatch but it became an issue when you have more than one stopwatch. And in the vector search algorithm, every seconds counts. So my search for alternatives led me to this
this performant and modern way introduced in .NET 7.

This is how it's done

long startTime = Stopwatch.GetTimestamp();
// Your code: Doing something e.g Thread.Sleep(3000);
TimeSpan elapsedTime = Stopwatch.GetElapsedTime(startTime);

With this new approach:

  • you are dont need to create a new Stopwatch instance hence no memory allocations on the heap, making it ideal for performance-critical paths.

  • The underlying timestamp for the Stopwatch methods is monotonic i.e. they are not affected by time changing due to Network Time Protocol (NTP) time sync changes or other sources of system time change.

  • The code is also simple and clear about its intent. I often see people forget to stop the StopWatch in the previous style. This new style is clean.
    Nick Chapsas gave a nice video talk about this as well

As i mentioned earlier, there are other ways to measure how long it takes to execute a method or function in .NET

  1. Through Professional tools like
    Visual studio Performance tool
    BenchmarkDotNet
    DotTrace Profiler by Rider, Dynatrace
    Datadog

  2. DateTime and TimeSpan
    Using DateTime, you can register the time before and after the execution of the code that you want to measure and

DateTime start = DateTime.UtcNow;
// Your code: Doing something e.g Thread.Sleep(3000);
DateTime end = DateTime.UtcNow;
TimeSpan timeDiff = end - start;
Console.WriteLine(Convert.ToInt32(timeDiff.TotalMilliseconds));

I wont recommend using the DateTime approach because it is not monotonic and relies on a lot of other variables as described in Nick Chapsas video

Thanks for reading. Hope you find this useful

API Trace View

Struggling with slow API calls? 🕒

Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay