86

Obviously I can do and DateTime.Now.After - DateTime.Now.Before but there must be something more sophisticated.

Any tips appreciated.

inspite
  • 27,551
  • 21
  • 73
  • 91

4 Answers4

96

System.Environment.TickCount and the System.Diagnostics.Stopwatch class are two that work well for finer resolution and straightforward usage.

See Also:

Community
  • 1
  • 1
ctacke
  • 65,117
  • 17
  • 91
  • 151
45

I would definitely advise you to have a look at System.Diagnostics.Stopwatch

And when I looked around for more about Stopwatch I found this site;

Beware of the stopwatch

There mentioned another possibility

Process.TotalProcessorTime

tafa
  • 6,858
  • 3
  • 33
  • 38
10

Use a Profiler

Your approach will work nevertheless, but if you are looking for more sophisticated approaches. I'd suggest using a C# Profiler.

The advantages they have is:

  • You can even get a statement level breakup
  • No changes required in your codebase
  • Instrumentions generally have very less overhead, hence very accurate results can be obtained.

There are many available open-source as well.

M.N
  • 10,197
  • 13
  • 44
  • 49
  • There are also disadvantages to using a profiler: the information is _post factum_, instrumentation is necessary still, not suitable to be kept in production code (we may want to measure working applications, not just during development). And last: profiling may sometimes be overkill. – Tomasz Gandor Mar 04 '13 at 11:44
4

Tickcount is good, however i suggest running it 100 or 1000 times, and calculating an average. Not only makes it more measurable - in case of really fast/short functions, but helps dealing with some one-off effects caused by the overhead.

FooLman
  • 427
  • 4
  • 11