I am building an application in .NET (not important what language, it is a language of the framework). I need to count how much time passes from an instruction to another. I need, so, to measure time.
How to do this using .NET libraries? Which one is the right namespace/class to use? Thank you
System.Diagnostics.Stopwatch
is probably what you want to use for this purpose, but keep in mind that whileStopwatch
is highly granular it is not especially accurate for long time periods. For example, if you start aStopwatch
and let it run for exactly 24 hours (as measured by an independent clock or the computer's system clock), it will show an elapsed time of 24 hours plus 5-10 seconds (not milliseconds).So, if you want to measure very short durations, use
Stopwatch
. If the durations you wish to measure are longer (on the order of a few minutes or more), you should instead make calls toDateTime.UtcNow
at the start and end of your sequence, and calculate the difference as aTimespan
.