What is the best way to measure execution time of a function?

C#PerformanceBenchmarkingExecution Time

C# Problem Overview


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

Any tips appreciated.

C# Solutions


Solution 1 - C#

Solution 2 - C#

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

Solution 3 - C#

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.

Solution 4 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIan GView Question on Stackoverflow
Solution 1 - C#ctackeView Answer on Stackoverflow
Solution 2 - C#tafaView Answer on Stackoverflow
Solution 3 - C#M.NView Answer on Stackoverflow
Solution 4 - C#FooLmanView Answer on Stackoverflow