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


Monday, February 16, 2009 | Comments (2) | 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

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);

1/29/2010 4:10:08 PM | by mr naidu

New Comment

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