Favour Parallel Streams for Simple cases

The Getting Started Tutorial for Akka actors is a parallel solution for getting Pi approximation. Basically you have a master actor that hands parts of the operation to worker actors in a Round Robin fashion and aggregates the result to form the final approximation.

All great, all brilliant.

I did some basic measurements on my machine (2.3 GHz Intel Core i7).
Running the example 4 times Using actors.

   main(){
   
   int nrOfElements = 10000;
   int workers = 4;
   calculateUsingActors(workers, nrOfElements, 10000);
   calculateUsingActors(workers, nrOfElements, 10000);
   calculateUsingActors(workers, nrOfElements, 10000);
   calculateUsingActors(workers, nrOfElements, 10000);
   }
   void calculateUsingActors(final int nrOfWorkers, final int nrOfElements, final int nrOfMessages) {
    ActorSystem system = ActorSystem.create("PiSystem");
    final ActorRef listener = system.actorOf(new Props(Listener.class), "listener");
    ActorRef master = system.actorOf(new Props(() -> {
            return new Master(nrOfWorkers, nrOfMessages, nrOfElements, listener);
        }), "master");

     master.tell(new Calculate());

   }

Results:

3.1415926435897883  894 milliseconds
3.1415926435897883  956 milliseconds
3.1415926435897883  921 milliseconds
3.1415926435897883  844 milliseconds

I implemented the same algorithm using parallel streams in a single Java expression and achieved better performance

double calculateUsingParallelStream(int nrOfElements){
  double pi = IntStream.range(0, nrOfElements)
              .parallel()
              .mapToDouble(c -> calculatePiFor(c, nrOfElements))
              .reduce((c, c1) -> c + c1)
              .getAsDouble();
  return pi;
}

double calculatePiFor(int start, int nrOfElements) {
  double acc = 0.0;
   for (int i = start * nrOfElements; i <= ((start + 1) * nrOfElements - 1); i++) {
      acc += 4.0 * (1 - (i % 2) * 2) / (2 * i + 1);
   }
   return acc;
}

Results:

3.141592643589785  235 milliseconds
3.141592643589785  122 milliseconds
3.141592643589785  119 milliseconds
3.141592643589785  123 milliseconds
Advertisements

Leave a Reply

Name and email address are required. Your email address will not be published.

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

You may use these HTML tags and attributes:

<a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <pre> <q cite=""> <s> <strike> <strong> 

%d bloggers like this: