What is the fastest most efficient way to sumUp all matrix elements parallel in .net 4.0 ?
using Parallel.For end in inner loop making lock(objectLock) { result += matrix[i, j] } is 2 times slowwer the开发者_Go百科n sequential approach.
thanks for any hints, bye
ParallelEnumerable.Sum
knows how to do the sum without needing either locking or interlocked operations (I assume it sums subsets on each thread, and then sums those results).
Assuming your matrix is IEnumerable<IEnumerable<numeric>>
:
var sum = (from row in matrix.AsParallel()
select row.Sum()).Sum();
The AsParallel
means the rows are processed in parallel, but the inner (column) sum is just Enumerable.Sum
(unless the rows are very long, the overhead of concurrency will overwhelm any possible benefits).
Well you can consider your martrix[m,n] to m arrays whose length is n and then sum the m arrays parallelly. And by the way, you shouldn't use lock
here, use Interlocked.Add
instead. I'm busy now, I'll write an example if I have time then.
Use static variables for i,j and result without using lock
精彩评论