开发者

Using Parallelization for relatively large loops

开发者 https://www.devze.com 2023-01-20 09:26 出处:网络
I have an 8-core CPU machine with 8 GB memory. Logically the following code can be done in parallel, but since the loop exposes more than enough opportunities for parallelism since I have far fewer co

I have an 8-core CPU machine with 8 GB memory. Logically the following code can be done in parallel, but since the loop exposes more than enough opportunities for parallelism since I have far fewer cores available than the size of the loop. Second, every delegate expression allocates some memory to hold the free variables. Is it recommended to use parallel for in this case?

also will separating the 2 parallel for's into 2 task improve the performance in this case??

     private static void DoWork()
    {

        int end1 = 100; // minimum of 100 values; 
        int end2 = 100; // minimum of 100 values;


        Task a = Task.Factory.StartNew(
            delegate
            {
                Parallel.For(0, end1, delegate(int i)
                {
                    // independent work                     
                });
            }
        );

        Task b = Task.Factory.StartNew(
            delegate
            {
       开发者_运维知识库         Parallel.For(0, end2, delegate(int i)
                {
                    // independent work                        
                });
            }
        );

        a.Wait();
        b.Wait();         
    }


also will separating the 2 parralel for's into 2 task improve the performance in this case??

Not noticeably, and you could easily harm performance.

The TPL is especially designed to provide load balancing, let it do its job.

The main points here that are your concern:

  • the 'work' should really be independent
  • the 'work' should be non-trivial, ie computationally intensive and considerably more than just adding a few numbers
  • the 'work' should avoid I/O (as much as possible)


  • Leave the load balancing to the framework by calling "Partitioner.Create".
  • Try creating a ParallelOptions object and pass it to Parallel.For. Try out with different MaxDegreeOfParallelism and tune your code based on the results, this number can be more than the no. of cores in your system. This has worked for me.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号