Click here to Skip to main content
15,891,652 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I learnt that java provides parallel streams for using multiple threading easily. So I tried to calculate sum of array both sequencially using for loop and using parallel stream.
But the output I got is not satisfying. Here is my Code=

public static void main(String[] args) {
		
		int arr[]=new int[10000];
		for(int i=0;i<10000;i++)	arr[i]=i;
		
		int sum=0;		//Sequential Sum
		long startTime=System.nanoTime();
		for(int i=0;i<10000;i++) sum+=arr[i];
		long seqTime=(System.nanoTime()-startTime);
		
		sum=0;		//Parallel Sum Using Stream
		startTime=System.nanoTime();
		sum=Arrays.stream(arr)
		.parallel()
		.sum();
		long parTime=(System.nanoTime()-startTime);
		System.out.println(parTime-seqTime);   // parallel - sequential
	}


Output :
15802200


I think output should be negative as parallel time should be less than sequential time.

What I have tried:

I tried to search if someone have faced this problem but could not relate any problem specifically to mine.
Posted
Updated 15-May-20 23:17pm

1 solution

Running a simple operation like that in parallel adds an overhead to the processor which may mean that it does not actually run faster than a simple sequence. Adding 10,000 integers in sequence will always run quite fast owing to pipelining and other optimised operations.

[edit]
I have just discovered the flaw in your test, you are not comparing like for like. In the first case you are just adding the numbers to get the sum, which is very fast at the processor level. However in your parallel test you are using Arrays.stream to convert the array to an IntStream (Java Platform SE 8 )[^] object, which adds a considerable overhead. If you change the first loop code to the following it is a much more valid test:
Java
sum=Arrays.stream(arr).sum(); // a sequential summation

So when I ran that I got the following results:
Sequential time: 18676400
  Parallel time: 12258900

I ran a few more tests and the parallel run was always faster.
[/edit]
 
Share this answer
 
v4
Comments
[no name] 16-May-20 9:22am    
+5. Also for the follow up and the test.
Richard MacCutchan 16-May-20 10:34am    
Thanks. It's amazing what you can learn just by reading the documentation.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900