Time Your Code
Timing code isn't difficult. You can use the DateTime.Now property
to capture the current date and time down to the millisecond. However,
this approach isn't perfect. Constructing the DateTime object takes a short time, and that
little bit of latency can skew the time you record for short operations.
Serious profilers need a better approach, one that uses low-level
systems calls and has no latency.
Note
The new Stopwatch class allows you to track how fast your code executes with unparalleled precision.
How do I do that?
In .NET 2.0, the best way to time your code is to use the new
Stopwatch class in the System.Diagnostics namespace. The Stopwatch class is refreshingly simple to
use. All you need to do is create an instance and call the Start( ) method.
When you're finished, call Stop( ).
Example 6-8 shows a simple test that times how long a loop takes to finish. The elapsed time is then displayed in several different ways, with different degrees of precision.
Example 6-8. Timing a loop
Module TimeCode Sub Main( ) Dim Watch As New Stopwatch( ) Watch.Start( ) ' Delay for a while. For i As Integer = 1 To 1000000000 Next Watch.Stop( ) ' Report the elasped time. Console.WriteLine("Milliseconds " & Watch.ElapsedMilliseconds) Console.WriteLine("Ticks: " & Watch.ElapsedTicks) Console.WriteLine("Frequency: " & Stopwatch.Frequency) Console.WriteLine("Whole Seconds: " & Watch.Elapsed.Seconds) Console.WriteLine("Seconds (from TimeSpan): " & Watch.Elapsed.TotalSeconds) Console.WriteLine("Seconds ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access