157 recommendations for writing high-quality code to improve C # programs--recommendation 88: Parallelism is not always faster

Source: Internet
Author: User

Recommendation 88: Parallelism is not always faster

Parallel to the background tasks and task management, will bring some overhead, if a job can be completed quickly, or the loop body is small, then the speed of parallel may be slower than non-parallel.

Looking at this example, we compare the time consumption in both synchronous and parallel states:

Static voidMain (string[] args) {Stopwatch Watch=NewStopwatch (); Watch.      Start ();      Doinfor (); Watch.       Stop (); Console.WriteLine ("Synchronization time: {0}", watch.       Elapsed); Watch.      Restart ();      Doinparallefor (); Watch.      Stop (); Console.WriteLine ("Parallel time consuming: {0}", watch.       Elapsed);  Console.readkey (); }   Static voiddosomething () { for(inti =0; I <Ten; i++) {i++; }  }   Static voiddoinfor () { for(inti =0; I < $; i++) {dosomething (); }  }   Static voiddoinparallefor () {Parallel.For (0, $, (i) = ={dosomething ();  }); } 


The above code in the author's current dual-core PC output is:
Synchronization time: 00:00:00.0005583
Concurrent Time: 00:00:00.0033604


It can be seen that synchronization took only 0.55 milliseconds, while parallelism used 3.3 milliseconds to complete the work.

Now, to simulate getting the loop body to do more, change the loop body in the DoSomething method from 10 to 10000000. The result of the operation is:
Synchronization time: 00:00:01.3059138
Concurrent Time: 00:00:00.6560593


When the loop body needs to do more work, we find that synchronization takes 1.3 seconds to complete the work, while in parallel the work is done in only 0.6 seconds.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--recommendation 88: Parallelism is not always faster

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.