0

Cosider example for scala time funciton measuring:

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
}

Source taken from here.

Now try this code:

object MapTimeMeasure {
  def main(args: Array[String]): Unit = {
    val intToString: Int => String = x => s"$x"
    val intToString2: Int => String = time (intToString)
  }
}

And you will see Elapsed time in the logs. So this time function can be used only for measuring time invocation "right now". But how to measure time for function without invocation? E.g. time just wraps function and executes it only when wrapped funciton is called not when time invocated itself. How to do this in scala?

Cherry
  • 31,309
  • 66
  • 224
  • 364
  • I neither understand what you want, nor do I understand what your code is doing. The `intToString` value is just a constant function literal, it doesn't do anything at all. Passing it to `time` doesn't make any sense, because you are measuring only the time that `time` itself is taking, and nothing else. – Andrey Tyukin Mar 27 '18 at 12:26
  • 1) `intToString` is just for example, (look at realted question) there can be any different function to pass in time. 2) the problem is `time` invocation leads to "time measuring" while it is needed to just chain funciton calls. – Cherry Mar 27 '18 at 12:36
  • Just pass the function in as a T=>R. You have tried to make it the same as call-by-name, but there is a slight but subtle difference between these forms. Your invocation will have to be adjusted too--as now you aren't passing in an Int at all so, as @AndreyTyukin says, you aren't actually *doing* anything. – Phasmid Mar 27 '18 at 13:50

1 Answers1

0

In your example time is called only once when you define function intToString2 but you probably want to call time every time function is called

val intToString: Int => String = x => s"$x"
val intToString2: Int => String = i => time (intToString(i))

and you can write decorator function that measures time

def timeF[A,B](func: A=>B): A=>B = {
  a => time(func(a))
}

val intToString: Int => String = x => s"$x"
val intToString2: Int => String = timeF(intToString)
vindev
  • 2,240
  • 2
  • 13
  • 20
Nazarii Bardiuk
  • 4,272
  • 1
  • 19
  • 22