HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Timing Project Euler Problem 1

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
timingprojecteulerproblem

Problem

Is there a better way to time the functions and print the result and function name dynamically?

package project_euler
object Timers extends App{

  def time[R](f: => R): Unit = {
        val t0 = System.nanoTime()
        val r = f
        val t1 = System.nanoTime()

        val t = (t1-t0)/1000

    println(s"The result is: $r time taken $t ms ")
    // print also the name of the function f**

  }

   /*
    * Problem 1 project Euler
    * If we list all the natural numbers below 10 that are multiples of 3 or 5,
    * we get 3, 5, 6 and 9.
    * The sum of these multiples is 23.
    * Find the sum of all the multiples of 3 or 5 below 1000.
    * */

   //functional implementation  
   def func = (0 until 1000).filter(x => x % 3 ==0  || x % 5 ==0).sum

   //imperative implementation
   def imper = {
     var i,sum = 0

     while (i < 1000) {
      if( i % 3 ==0 || i % 5 ==0)
          sum +=i

      i+=1 //increase counter
    }
    sum
  }                           
   time (func)
   time (imper)
  }

Solution

So, I pasted your code into my IDE and ran it in the debugger, and there isn't really any way to do exactly what you want to do. The function object doesn't appear to have any knowledge of anything other than how to call it.

Your best bet seems to be to modify the timing function to something like this:

def time[R](f: => R, name: String): Unit = {
    val t0 = System.nanoTime()
    val r = f
    val t1 = System.nanoTime()

    val t = (t1-t0)/1000

    println(s"The result of $name is: $r time taken $t ms ")
  }


And then your call would be something like this:

time (func, "func")


In a larger app, if you needed to pass around functions with their name, you could create a small object such as:

class Caller[R](f: => R, name: String) {
  def time(): Unit = {
    val t0 = System.nanoTime()
    val r = f
    val t1 = System.nanoTime()

    val t = (t1-t0)/1000

    println(s"The result of $name is: $r time taken $t ms ")
  }
}


Create it like so:

val a = new Caller(func, "func")


And call it like so:

a.time()

Code Snippets

def time[R](f: => R, name: String): Unit = {
    val t0 = System.nanoTime()
    val r = f
    val t1 = System.nanoTime()

    val t = (t1-t0)/1000

    println(s"The result of $name is: $r time taken $t ms ")
  }
time (func, "func")
class Caller[R](f: => R, name: String) {
  def time(): Unit = {
    val t0 = System.nanoTime()
    val r = f
    val t1 = System.nanoTime()

    val t = (t1-t0)/1000

    println(s"The result of $name is: $r time taken $t ms ")
  }
}
val a = new Caller(func, "func")

Context

StackExchange Code Review Q#57405, answer score: 6

Revisions (0)

No revisions yet.