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

拈花ヽ惹草 提交于 2019-11-28 14:26:32

问题


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

Any tips appreciated.


回答1:


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

See Also:

  • Is DateTime.Now the best way to measure a function’s performance?
  • High resolution timer in .NET
  • Environment.TickCount vs DateTime.Now
  • What’s the best way to benchmark programs in Windows?



回答2:


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




回答3:


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.




回答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.



来源:https://stackoverflow.com/questions/380919/what-is-the-best-way-to-measure-execution-time-of-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!