Skip to content

Simple performance stopwatch

Jon P Smith edited this page Dec 14, 2024 · 16 revisions

I often needed to know how long a process took. I do use BenchmarkDotNet, but often I want a simpler method. My solution is TimeThings. TimeThings is very easy to use and I usually TimeThings in my Xunit unit tests (it only add ~2ms. to the test), BUT you must understand that most unit tests run in parallel, which affect the time a process takes (see this section on how to get the correct time).

An example of using the TimeThings in Xunit unit tests

[Fact]
public class TestTimeThings(ITestOutputHelper output) 
//The ITestOutputHelper is Xunit's way to return a string to your Test Explorer
{
    public void TestWithTimeThings()
    {
        //SETUP                  
        //your test setup

        //ATTEMPT
        using (new TimeThings(output))
        {
            //your process you need to test and 
        }

        //VERIFY
        //your test checks
    }

The default message returns a string with a time, e.g., "took 1.64 ms.", which comes up in your Test Explorer (assuming that the your process doesn't throw and Exception).

Clone this wiki locally