Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Stopwatch be used in production code?

I need an accurate timer, and DateTime.Now seems not accurate enough. From the descriptions I read, System.Diagnostics.Stopwatch seems to be exactly what I want.

But I have a phobia. I'm nervous about using anything from System.Diagnostics in actual production code. (I use it extensively for debugging with Asserts and PrintLns etc, but never yet for production stuff.) I'm not merely trying to use a timer to benchmark my functions - my app needs an actual timer. I've read on another forum that System.Diagnostics.StopWatch is only for benchmarking, and shouldn't be used in retail code, though there was no reason given. Is this correct, or am I (and whoever posted that advice) being too closed minded about System.Diagnostics? ie, is it ok to use System.Diagnostics.Stopwatch in production code? Thanks Adrian

like image 413
Adrian Avatar asked May 10 '10 18:05

Adrian


People also ask

Does stopwatch affect performance?

So there is no reason it could affect the performance of your code, at least not significantly. Stopwatch was designed specifically for accurate time measurements, so you can be sure it is thoroughly optimized. It is also much more accurate than comparing successive values of DateTime.

Does stopwatch have a limit?

The value of this field is equivalent to Int64. MaxValue ticks. The string representation of this value is positive 10675199.02:48:05.4775807, or slightly more than 10,675,199 days.


1 Answers

Under the hood, pretty much all Stopwatch does is wrap QueryPerformanceCounter. As I understand it, Stopwatch is there to provide access to the high-resolution timer - if you need this resolution in production code I don't see anything wrong with using it.

like image 127
Steve Dennis Avatar answered Sep 20 '22 11:09

Steve Dennis