I recently came across a pair of functions from js-land that I rather like:
console.time("CalcPrimes");
// Go calculate primes
console.timeEnd("CalcPrimes");
// Outputs something like > CalcPrimes: 2150ms
Behind the scenes it's a simple dictionary that records the starting timestamp and prints duration by subtracting start time from end time.
Compare this with .NET code:
var sw = new Stopwatch();
sw.Start();
// Go calculate primes
sw.Stop();
Trace.WriteLine("CalcPrimes:" + sw.ElapsedMilliseconds);
My naive code requires twice as many lines to do the same thing (Note: you can do it in just two). However, I still have to manually format output. When I have to inject non-core logic into my app, I want the least clutter possible. Mostly, I'm against the duplicate logic to format the output everywhere I might time something.
- Are there existing solutions in the .NET world for a less verbose timer/stopwatch?
- If not, what dangers should I be aware of in creating a similar solution to the js code? (or example, should I use a
Dictionary<String, Stopwatch>
instead of saving offDate.Now
due to precision issues?