Measure code execution time

From time to time there is a need to measure how much time it takes for a certain fragment of code to execute.

First thought how to do this would probably be something like this:

            DateTime start = new DateTime();
            TimeSpan time = DateTime.Now.Subtract(start);
            Console.WriteLine("Time taken: {0}", time.Ticks.ToString());

In .NET 2.0 however there is a class tailored fir this task: System.Diagnostics.Stopwatch.

To use it you would rewrite code above to something like:

            Stopwatch stopwatch = new Stopwatch();
            Console.WriteLine("Time measured: {0}", stopwatch.ElapsedTicks.ToString());

To learn more, visit MSDN site.