C# has a Stopwatch class that is pretty accurate at timing things. In fact, it uses some low-level operating system stuff to make sure to get exact timings. This means it can be more accurate than comparing two different DateTime.Now instances.
I’ve found myself using the Stopwatch occasionally, but it always is kind of a bugger for unit testing. If you only execute a block of code when the Stopwatch has been running for more than a certain amount of time, you’re left with a couple of options:
- Make the amount of elapsed time you’re looking for a variable so that you can change it in the unit test to suit your needs
- This probably makes the most sense, but programmers aren’t always sensible.
- Abstract the Stopwatch class by creating an interface, which is then mockable using Moq or other similar mocking framework.
- This is alright, since it abstracts away the implementation… but, really, are you going to be using a different implementation of Stopwatch anywhere other than for tests?
- Use Reflection to time travel, because you’re some kind of bad-ass time wizard
- … Time travel!
Naturally, I want to be a wizard.
Reflection
The Stopwatch class has a private property field that you can set the value of to set the elapsed time.
The only trick here is that the private field _elapsed is in ticks, and there are 10,000 of them in one millisecond.