How many times have you wished to log how long a particular piece of code took to execute? Maybe you are trying to track average request time or some such metric, or maybe send a warning message when a stored procedure takes longer than 1 second to execute.
Well, you could do it with DateTime like so:
1: DateTime start = DateTime.Now;
2: SomeCodeToTime();
3: DateTime end = DateTime.Now;
4: Console.WriteLine("Method took {0} ms", (end - start).TotalMilliseconds);
But DateTime is imprecise for this sort of metric. You could also query the high resolution timer using Win32 API calls via PInvoke, but this is also very messy and more error prone.
So what’s a C# developer to do? Enter the Stopwatch class which is in the System.Diagnostics namespace. The Stopwatch class makes it clean and easy to use the high resolution timer through the convenience of a C# class:
1: var timer = Stopwatch.StartNew();
2: SomeCodeToTime();
3: timer.Stop();
4: Console.WriteLine("Method took {0} ms", timer.ElapsedMilliseconds);
Much more precise and very clean. Note there is a static factory method to create a Stopwatch and immediately start it. You also have the option of creating using new and then starting manually as you choose.
05bd1254-1c1a-47a9-ade5-38e668c03196|0|.0