初学scala4——trait混入

最近在调优程序,总要对比程序执行的时间,之前都是在程序片段前后加上时间然后相减。

今天看了别人写的代码,使用了trait混入,减少了很多同样代码,mark一下,也加深对trait混入的理解。

trait TMetrics {
  def timeIt[T](desc: String)(f: () => T): T = {
    println(s"Thread:${Thread.currentThread().getId} | BEGIN | ${desc} | ${new Date()}")
    val res = f.apply()
    println(s"Thread:${Thread.currentThread().getId} | END   | ${desc} | ${new Date()}")
    res
  }
}

object MeTest extends TMetrics with App{
    timeIt("Test")(() => TimeUnit.SECONDS.sleep(3))
}

执行结果

Thread:1 | BEGIN | Test | Mon Feb 06 20:37:06 CST 2017
Thread:1 | END   | Test | Mon Feb 06 20:37:09 CST 2017

 

posted @ 2017-02-06 23:38  JamieLybo  阅读(123)  评论(0编辑  收藏  举报