Possible Duplicates:
Is DateTime.Now the best way to measure a function's performance?
Stopwatch vs. using System.DateTime.Now for timing events
I have code which needs to run as fast as possible. To be able to log the execution time, I use the Stopwatch class. I suspect, Stopwatch may effect the performance in a bad way. Maybe using a DateTime difference may be more effective?
Which one do you think has better performance?
Stopwatch sw = new Stopwatch();
sw.Start();
int a = 5;
// Critical lines of code
long elapsedMs = se.Elapsed.TotalMilliseconds;
OR
DateTime startDate = DateTime.Now;
int a = 5;
// Critical lines of code
long elapsedMs = DateTime.Now.Subtract(startDate).TotalMilleseconds;
The Stopwatch
isn't doing anything between the calls to Start
and Stop
... It just stores the current timestamp (via QueryPerformanceCounter
) when you start it, and compare it to the current timestamp when you stop it. 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.Now
. ...