C# 测量函数执行时间的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/380919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to measure execution time of a function?
提问by inspite
Obviously I can do and DateTime.Now.After
- DateTime.Now.Before
but there must be something more sophisticated.
显然我可以做到并且DateTime.Now.After
-DateTime.Now.Before
但必须有更复杂的东西。
Any tips appreciated.
任何提示表示赞赏。
采纳答案by ctacke
System.Environment.TickCountand the System.Diagnostics.Stopwatchclass are two that work well for finer resolution and straightforward usage.
System.Environment.TickCount和System.Diagnostics.Stopwatch类是两个适用于更精细分辨率和直接使用的类。
See Also:
也可以看看:
回答by tafa
I would definitely advise you to have a look at System.Diagnostics.Stopwatch
我肯定会建议你看看 System.Diagnostics.Stopwatch
And when I looked around for more about Stopwatch I found this site;
当我四处寻找有关秒表的更多信息时,我找到了这个网站;
There mentioned another possibility
提到了另一种可能性
Process.TotalProcessorTime
Process.TotalProcessorTime
回答by FooLman
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.
Tickcount 很好,但是我建议运行它 100 或 1000 次,并计算平均值。不仅使它更可测量 - 在真正快速/短函数的情况下,而且有助于处理由开销引起的一些一次性影响。
回答by M.N
Use a Profiler
使用探查器
Your approach will work nevertheless, but if you are looking for more sophisticated approaches. I'd suggest using a C# Profiler.
尽管如此,您的方法仍然有效,但如果您正在寻找更复杂的方法。我建议使用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-sourceas well.
还有许多可用的开源软件。