performance issue with Nondeterminism

21 views
Skip to first unread message

Tiger Chan

unread,
Jun 15, 2016, 11:11:07 PM6/15/16
to scalaz
Hi, could anyone explain why concurrent process with nondeterminism is slower than sequential approach? attached below is my demo code:

def seqFib(n: Int): Task[Int] =  n match {


  case 0 | 1 => Task now  1


  case n => {


    for {


      x <- seqFib(n-1)


      y <- seqFib(n-2)


    } yield x + y


  }


 }                                                //> seqFib: (n: Int)scalaz.concurrent.Task[Int]


 //concurrent approach


 def parFib(n: Int): Task[Int] = n match {


    case 0 | 1 => Task now 1


    case n => {


       val ND = Nondeterminism[Task]


       for {


         pair <- ND.both(parFib(n-1), parFib(n-2))


         (x,y) = pair


       } yield x + y


    }


 }                                                //> parFib: (n: Int)scalaz.concurrent.Task[Int]


 def msFib(n: Int, fib: Int => Task[Int]) = for {


   b <- Task now { System.currentTimeMillis() }


   a <- fib(n)


   e <- Task now { System.currentTimeMillis() }


 } yield (a, (e-b))                               //> msFib: (n: Int, fib: Int => scalaz.concurrent.Task[Int])scalaz.concurrent.T


                                                  //| ask[(Int, Long)]


 


 msFib(20, parFib).unsafePerformSync              //> res3: (Int, Long) = (10946,315)


 msFib(20, seqFib).unsafePerformSync              //> res4: (Int, Long) = (10946,16)



thanks!
Reply all
Reply to author
Forward
0 new messages