1

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

1
  • Use StopWatch as suggested and don't forget to compile in release mode. Commented Feb 15, 2011 at 8:59

5 Answers 5

3

Its always better to use System.Diagnostics.Stopwatch

Check this link for more details. Performance Tests: Precise Run Time Measurements with System.Diagnostics.Stopwatch

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

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.

Comments

2

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.

Comments

2

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 :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.