Advertisement
Guest User

Untitled

a guest
May 21st, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.04 KB | None | 0 0
  1. object SynteticTest {
  2.  
  3.   implicit val ec: ExecutionContext = ExecutionContext.global
  4.   def createFuture(dummy: Int): Int => Future[Int] = x => Future.successful(x + dummy)
  5.  
  6.   def testWithFutures(futures: Seq[Int => Future[Int]]): Future[Int] ={
  7.  
  8.  
  9.     futures.foldLeft(Future.successful(0)) {
  10.       (result, op) => {
  11.         result.flatMap{ rs =>
  12.           op(rs)
  13.         }
  14.       }
  15.     }
  16.  
  17.   }
  18.  
  19.  
  20.  
  21.   def testPlain(): Unit = {
  22.     def simpleClojure(arg: Int): Int => Int = x => x + arg
  23.  
  24.     val listoffuns: Seq[Int => Int] = (1 to 20000).map(simpleClojure)
  25.     listoffuns.foldLeft(0){ (o1, o2) =>
  26.       o1 + o2.apply(o1)
  27.     }
  28.  
  29.   }
  30.  
  31.   def main(args: Array[String]): Unit = {
  32.     val ts = System.currentTimeMillis()
  33.  
  34.     testWithFutures(Seq.fill(20000)(1).map(createFuture)).andThen {
  35.       case Success(rs) => println(s"Async took = ${System.currentTimeMillis() - ts}")
  36.     }
  37.  
  38.     val ts2 = System.currentTimeMillis()
  39.     testPlain()
  40.     println(s"Sync took ${System.currentTimeMillis() - ts2}")
  41.  
  42.     Thread.sleep(10000)
  43.  
  44.   }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement