C# 中方法调用的基准测试
我正在寻找一种方法来对 C# 中的方法调用进行基准测试。
我已经为大学作业编写了一个数据结构,并且只是想出了一种稍微优化的方法,但这种方法会在所有情况下增加一点开销,同时将 O(n) 调用变成 O(1)在一些。
现在我想针对测试数据运行这两个版本,看看是否值得实施优化。我知道在 Ruby 中,您可以将代码包装在 Benchmark 块中,并让它输出在控制台中执行该块所需的时间 - 有类似的东西可用于 C# 吗?
I'm looking for a way to benchmark method calls in C#.
I have coded a data structure for university assignment, and just came up with a way to optimize a bit, but in a way that would add a bit of overhead in all situations, while turning a O(n) call into O(1) in some.
Now I want to run both versions against the test data to see if it's worth implementing the optimization. I know that in Ruby, you could wrap the code in a Benchmark block and have it output the time needed to execute the block in console - is there something like that available for C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
以下是我通过反复试验发现的一些事情。
Here are some things I've found by trial and errors.
Thread
object can give better and more stable results. I don't know why.Thread.Sleep
for whatever reason before executing the benchmark. This will only make things worse. I don't know why. Possibly due to the JITter.您可以使用内置的 Stopwatch 类 来“提供您可以使用一组方法和属性来准确测量经过的时间。”如果您正在寻找手动方法来完成此操作。但不确定自动化。
You could use the inbuilt Stopwatch class to "Provides a set of methods and properties that you can use to accurately measure elapsed time." if you are looking for a manual way to do it. Not sure on automated though.
我从 Jon Skeet 的基准测试方法中窃取了以下大部分内容:
I stole most of the following from Jon Skeet's method for benchmarking:
分析器提供了最好的基准,因为它们可以诊断您的所有代码,但是它们会减慢速度。分析器用于查找瓶颈。
为了优化算法,当您知道瓶颈在哪里时,请使用名称字典-->秒表,以跟踪运行时的性能关键部分。
Profilers give the best benchmarks since they diagnose all your code, however they slow it down a lot. Profilers are used for finding bottlenecks.
For optimizing an algorithm, when you know where the bottlenecks are, use a dictionary of name-->stopwatch, to keep track of the performance critical sections during run-time.
听起来您想要一个分析器。我本人强烈推荐 EQATEC 分析器,它是我尝试过的最好的免费工具。与简单的秒表方法相比,这种方法的好处在于它还提供了某些方法/块的性能细分。
Sounds like you want a profiler. I would strongly recommend the EQATEC profiler myself, it being the best free one I've tried. The nice thing about this method over a simple stopwatch one is that it also provides a breakdown of performance over certain methods/blocks.
从 Yuriy 的答案中窃取(并修改):
通常一个特定的方法必须初始化一些东西,并且您并不总是希望将这些初始化成本包含在总体基准中。此外,您还希望将总执行时间除以迭代次数,以便您的估计或多或少独立于迭代次数。
Stolen (and modified) from Yuriy's answer:
Often a particular method has to initialize some things, and you don't always want to include those initialization costs in your overall benchmark. Also, you want to divide the total execution time by the number of iterations, so that your estimate is more-or-less independent of the number of iterations.