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


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.


Yes, System.Diagnostics does sound like it is for debugging only, but don't let the name deceive you. The System.Diagnostics namespace may seem a bit scary sounding for use in production code at first (it did for me), but there are plenty of useful things in that namespace.

Some things, such as the Process class, are useful for interacting with the system. With Process.Start you can start other applications, launch a website for the user, open a file or folder, etc.

Others things, such as the Trace class, can help you track down bugs in production code. Granted, you will not always use them in production code, but they are very useful for logging and tracking down that elusive bug on a remote machine.

Don't worry about the name.


You say you've read on another forum not to use classes from System.Diagnostics in production. But the only source you should worry about is Microsoft, who created the code. They say that the StopWatch class:

Provides a set of methods and properties that you can use to accurately measure elapsed time.

They don't say, "except in production".