使用 hprof 分析 scala for 循环
据传闻,scala 中的 for 循环比 while 循环慢。
慢:
for (i <- 0 until 10000) {
f(i)
}
快:
var i = 0
while (i < 10000) {
f(i)
i += 1
}
如何使用 hprof 判断 for 循环是否是代码中的瓶颈?我正在使用 -agentlib:hprof=cpu=samples
分析我的代码,“CPU SAMPLES”部分中的方法是什么?
我想知道优化工作的重点在哪里。 for循环是瓶颈吗?
Word on the street is that for loops in scala are slower than while loops.
Slow:
for (i <- 0 until 10000) {
f(i)
}
Fast:
var i = 0
while (i < 10000) {
f(i)
i += 1
}
How do I use hprof to tell whether the for loops are the bottleneck in my code? I'm profiling my code using -agentlib:hprof=cpu=samples
, what would the method be in the "CPU SAMPLES" section?
I'd like to know where to focus my optimization efforts. Are for loops the bottleneck?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您可能会更幸运地使用专门用于分析的工具,例如 yourkit 或 visualvm。
他们通常有接口来捕获 CPU 样本,然后深入查看哪些调用消耗了最多的 CPU 周期。
任何类型的瓶颈都会出现(比如占用 95% 的 CPU 时间),然后您可以深入研究,直到看到您的(或库)的哪些方法位于这些热点的调用堆栈上。然后你可以看看是否涉及for循环。
I think you may have more luck with tools specialized with profiling such as yourkit or visualvm.
They usually have interface to capture CPU sample and then drill down to see what calls consumed most CPU cycles.
Bottlenecks of any kind would show up (like taking 95% of the CPU time) and then you could drill down until you see what methods of yours (or the library) is on the call stack for those hot spots. Then you can see if for loops are involved.
将每个循环放入其自己的方法中,然后比较这些方法所花费的时间。并使用足够的迭代来实际花费一些时间(或将其包装在另一个循环中)。 10000 次迭代需要几微秒;这对于分析器来说很难测量。尝试十亿次(或 10k 次迭代中的 100k 次迭代)。
另外,如果
f(i)
很昂贵,那么花费的时间将比循环花费的时间多得多。另外,如果f(i)
实际上没有做任何事情,它可能会完全被优化掉。因此,请确保它确实如此(例如,在某处更新计数器、计算总和或其他内容)。Put each loop in its own method, then compare the time taken by the methods. And use enough iterations to actually take some time (or wrap those in another loop). 10000 iterations should take microseconds; that's hard for a profiler to measure. Try a billion (or 100k iteratons of 10k iterations).
Also, if
f(i)
is expensive, that will take far more time than the loop will. Also, iff(i)
doesn't actually do anything, it might get optimized away entirely. So make sure it does (e.g. update a counter somewhere, compute a sum, or something).