Reputation: 43
I want to measure the performance of my code.. if I consider the time as a criterion I have this code
DateTime oldDate = new DateTime(2002,7,15);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = newDate - oldDate;
// Difference in days.
int differenceInDays = ts.Milliseconds ;
Question1: is this the only way that I can test the performance of my algorithm ? Question2: what are other criterion that C# provide to test the performance? Regards
Upvotes: 1
Views: 413
Reputation: 111940
If you truly want to use DateTime
(because it's easier to use), use UtcNow
instead of Now
. It's a little faster (because current date and time are stored in UTC format in Windows) and as an added bonus, you can test your program around the DST change time :-).
But yeah, use Stopwatch
.
Stopwatch watch = Stopwatch.StartNew();
watch.Stop()
Ah... very important... your code is wrong
ts.TotalMilliseconds
I did the same error yesterday, but I was measuring times around the second, so it was more difficult to notice :-)
Upvotes: 2
Reputation: 19938
You can use a profiler (tool based, for example with SlimTune) or measure the time with System.Diagnostics.Stopwatch
. It has better precision than the DateTime
hack.
Upvotes: 2
Reputation: 28692
use Stopwatch class
//Start a stopwatch:
var watch = Stopwatch.StartNew();
//Execute the code
watch.Stop(); //This stops the watch
The elapsed time can be measured by using Elapsed, ElapsedMilliSeconds and ElapsedTicks properties.
Upvotes: 3
Reputation: 55298
Its always better to use System.Diagnostics.Stopwatch
Check this link for more details. Performance Tests: Precise Run Time Measurements with System.Diagnostics.Stopwatch
Upvotes: 3
Reputation: 3461
Try using the StopWatch class. It has significantly higher resolution than the DateTime and TimeSpan classes.
Additionally, you can look at the Windows Performance Counters as a way of measuring performance while your application is running so that you can monitor the health of your application.
Upvotes: 2