Search code examples
.netperformancebenchmarking

How to measure code performance in .NET?


I'm doing some real quick and dirty benchmarking on a single line of C# code using DateTime:

long lStart = DateTime.Now.Ticks;
// do something
long lFinish = DateTime.Now.Ticks;

The problem is in the results:

Start Time [633679466564559902]
Finish Time [633679466564559902]

Start Time [633679466564569917]
Finish Time [633679466564569917]

Start Time [633679466564579932]
Finish Time [633679466564579932]

...and so on.

Given that the start and finish times are identical, Ticks is obviously not granular enough.

So, how can I better measure performance?


Solution

  • The Stopwatch class, available since .NET 2.0, is the best way to go for this. It is a very high performance counter accurate to fractions of a millisecond. Take a look at the MSDN documentation, which is pretty clear.

    EDIT: As previously suggested, it is also advisable to run your code a number of times in order to get a reasonable average time.