Scala 中可以制作作用域计时器吗?
我正在尝试制作一个计时器来测量范围的执行时间。我可以通过手动启动计时器,然后在范围末尾放置一些东西来停止计时器来完成此操作,但这是两倍的工作量。在 C++ 中,您可以创建一个计时器类,该类在调用其析构函数时进行评估,并在某些内容超出范围时调用析构函数,因此计时器会“自动”处理自身。由于 Scala 是一种托管语言,实例在被垃圾收集之前不会消失,因此依赖该方法在计时器方面基本上是无用的,除非我试图计算某些东西在被垃圾收集之前存活的时间。
下面是创建计时器的代码在离开作用域时自动求值的示例:
def someMethod(someVar: Int) {
val myTimer: ScopeTimer = ScopeTimer(startImmediately = true)
// Do some stuff
// Do more stuff
10 // Return some int value here
}
当方法返回 10
时,myTimer
将离开作用域和火。
在 Scala 中,有没有简单的方法可以让计时器来评估这样的作用域的执行时间?
I'm trying to make a timer that measures the execution time of a scope. I could do this by starting a timer manually, and then putting something at the end of a scope to stop the timer, but that's twice as much work. In C++ you can create a timer class that evaluates when its destructor is called, and destructors are called when something goes out of scope, so the timer takes care of itself "automagically". With Scala being a managed language, an instance won't disappear until it is garbage collection, so relying on that method is essentially useless in terms of a timer, unless I was trying to time how long something lived until it was garbage collected.
Here's an example of what the code for making a timer would look like if it auto-evaluated at the time it left scope:
def someMethod(someVar: Int) {
val myTimer: ScopeTimer = ScopeTimer(startImmediately = true)
// Do some stuff
// Do more stuff
10 // Return some int value here
}
As the method returned 10
, myTimer
would leave scope, and fire.
Is there any easy way of making a timer to evaluate the execution time of a scope like this, in Scala?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像这样的事情怎么样:
参数“op”作为按名称参数传递给 timedScope,因此只有在 timedScope 体内使用它时才会对其进行求值。
为了回答有关从对象调用的后续问题,它工作得很好:
How about something like this:
The parameter 'op' is being passed as a by-name parameter to timedScope so it isn't evaluated until it is used inside the body of timedScope.
And to answer your followup question about calling from an object, it works just fine: