How to measure performance of C# method in milliseconds?

You can use JetBrains dotTrace to find bottle neck methods of your application. So, how to measure performance of specific method? .NET framework since version 2.0 has Stopwatch class in System.Diagnostics namespace. You can use following snippet to measure 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 output would be:

2929.66815614834 ms


Posted on Monday, February 16, 2009 by | Comments (3) | Add Comment

Comments

Gravatar

Re:How to measure performance of C# method in milliseconds?

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 7/27/2009 2:32:27 AM by Dean Thomas #
Gravatar

Re:How to measure performance of C# method in milliseconds?

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

Posted on 1/29/2010 4:10:08 PM by mr naidu #
Gravatar

Re: How to measure performance of C# method in milliseconds?

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

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

New Comment

Your Name:
Email (for internal use only):
Comment:
 
Code above:

Categories

Recent Tweets

  • Simon Ince's Blog: Hierarchies with HierarchyID in SQL 2008 http://t.co/xSDwiF6rRS.
  • Visual Studio 2010 WAS painfully slow - CodeProject http://t.co/Usba1x6CZy

Valid HTML5