如何在 Scala 中分析方法? [英] How to profile methods in Scala?
问题描述
分析 Scala 方法调用的标准方法是什么?
What is a standard way of profiling Scala method calls?
我需要的是围绕一个方法的钩子,我可以使用它来启动和停止计时器.
What I need are hooks around a method, using which I can use to start and stop Timers.
在 Java 中,我使用方面编程,aspectJ,来定义要分析的方法并注入字节码以实现相同的目的.
In Java I use aspect programming, aspectJ, to define the methods to be profiled and inject bytecode to achieve the same.
在 Scala 中是否有更自然的方法,我可以在其中定义一堆要在函数之前和之后调用的函数,而不会在过程中丢失任何静态类型?
Is there a more natural way in Scala, where I can define a bunch of functions to be called before and after a function without losing any static typing in the process?
推荐答案
您是否希望在不更改要为其测量计时的代码的情况下执行此操作?如果您不介意更改代码,那么您可以执行以下操作:
Do you want to do this without changing the code that you want to measure timings for? If you don't mind changing the code, then you could do something like this:
def time[R](block: => R): R = {
val t0 = System.nanoTime()
val result = block // call-by-name
val t1 = System.nanoTime()
println("Elapsed time: " + (t1 - t0) + "ns")
result
}
// Now wrap your method calls, for example change this...
val result = 1 to 1000 sum
// ... into this
val result = time { 1 to 1000 sum }
这篇关于如何在 Scala 中分析方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!