Measuring Time
What is it about?
Sometimes we want to measure time in our C# applications to know how long an operation took. This can be used for logging and performance analysis.
Usually we perform these steps to measure how long something took:
- Get the starting time
- Do the operation
- Get the ending time
- Calculate the difference between starting and ending time.
How not to do it
Here are two examples of how you could do it, that you shouldn’t use.
Using DateTime.UtcNow
While this example is logically correct it is not optimal. DateTime.UtcNow
behind the scenes has some convoluted ways to calculate the timestamp, takes care of a lot of edge cases, but takes some time to calculate. This means that your measurement isn’t completely accurate.
Using Stopwatch
Both examples use the Stopwatch
class from Microsoft to do the measurements, which was created for the very use-case to measure time. The second example is basically the same as the first example StartNew
is just a wrapper method that creates a new Stopwatch
and starts it.
This example is also logically correct. However, Stopwatch
is a class, which means, that for every measurement of your operation a new object will be created on the heap. This isn’t really bad, as it doesn’t take up too much time, but whenever possible we should avoid allocating memory on the heap, which also means that the garbage collector won’t have to clean up anything. It should be mentioned - if you just measure the time once it doesn’t really matter if you do it this way. But if this in a production code that gets called thousands or millions of times, it might slow down your application.
How to do it
The following example still uses the Stopwatch
class. Using the static GetTimestamp
method, no object will be created on the heap, but a operating system call will be made in the background to get the current time in ticks. This will be a value of type long
and 10.000 ticks equals one millisecond. Wen can use the static GetElapsedTime
method on the Stopwatch
to calculate the correct TimeSpan
again.
or shorter but equivalent: