KARPACH

WEB DEVELOPER BLOG

How to measure performance of C# method in milliseconds?

You can use JetBrains dotTrace to find a bottle neck methods for your application. So, how to measure a performance of a specific method? .NET framework since version 2.0 has Stopwatch class in System.Diagnostics namespace. You can use the following snippet to measure a performance of your method:

public static void DummyLoop()
{
    for (int i = 0; i < 1000; i++)
    {
        System.Threading.Thread.Sleep(2);
    }
}

static void Main(string[] args)
{
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();
    DummyLoop();
    stopWatch.Stop();
    double ms = (stopWatch.ElapsedTicks \* 1000.0) / Stopwatch.Frequency;
    Console.WriteLine(string.Concat(ms.ToString(), " ms"));
    Console.ReadLine();
}

And the output would be:

2929.66815614834 ms

Posted on February 16, 2009 by

Comments

Posted on 7/27/2009 02:32:27 AM by Dean Thomas

We can save one line of code here :)

//This creates a new instance of Stopwatch, and starts it counting.
Stopwatch stopWatch = Stopwatch.StartNew();

Cheers,

Dean

Posted on 1/29/2010 04:10:08 PM by mr naidu

Console.WriteLine("{0}ms , stopWatch.ElapsedMilliseconds); 

Posted on 7/3/2012 02:47:42 AM by Pavel Vladov

Congratulations for the nice article! I have something to add though - note that there’s a lot of activity going on under the hood of the OS, which can steal some CPU time and slow down some of the tests. That’s why it is best to execute the tests multiple times and then remove the lowest and the highest times.

For more information take a look at: http://www.pvladov.com/2012/06/measure-code-performance.html