Taking Advantage of Parallelism in .NET

Microservices, Data stream Processing, Event-Driven Architecture, CQRS… a lot of terms and buzzwords that represents the capacity of run process asynchronously in our softwares.

And they are good, but lets have a little break to think what kind of power we have right in our hands: the modern CPUs.

They usually have more than one physical core, and still manage to emulate more.

Recently, I read that Microsoft will launch a new version of its operation system: Windows 10 Workstations edition for power users. It will support 4 physical CPUs.

So, lets take advantage of it.

Usually we use to think algorithms in sequential steps, and that is right, because it depends of the result of each interaction to go to next step. But apps usually have a lot of algorithms running, and in some cases they can be independent of the others. Also we have typical cases where it is possible have an independent thread running in the system. For example I/O Bound.

Have you thought if is really necessary freeze the whole system waiting a conclusion of a HTTP communication? What about write a lot of data in disk? If you have to post the same data to five different HTTP endpoints, can it done parallel?

But for now, lets learn how to use it with C#.

Lets assume a classical mathematical problem, factorial computation:

static int GetFactorial(int n)
{
    return (n >= 1) ? (n * GetFactorial(n - 1)) : 1;
}

So, lets calculate factorial of 900, 100000 times, in a simple way:

static void Main(string[] args)
{
    //pause to stabilize the system
    Thread.Sleep(1000);
    
    var stopwatch = new Stopwatch();
    stopwatch.Start();

    var number = 900;
    var timesToCalculate = 100000;

    // calculating N times the result of nuber factorial
    for (int i = 0; i < timesToCalculate; i++)
        GetFactorial(number);

    stopwatch.Stop();
    Console.WriteLine($"{number}! calculated {timesToCalculate} times took: {stopwatch.ElapsedMilliseconds}");
    Console.ReadLine();
}

And here we have the first result:

Let me introduce you the Task, a simple way to create threads in .NET.

There are a kind of “computer science philosophy” behind the difference and definitions, but a smart way to think can be: Tasks are easer to handle and work fine for computations with a result, like mathematical operations. Threads have a high cost to operation system, and a good use case can be something that you will constantly monitoring/handling.

Lets apply it to the code:

var tasks = new Task[timesToCalculate];

for (int i = 0; i < timesToCalculate; i++)
    tasks[i] = Task.Factory.StartNew(() => GetFactorial(number));

Task.WaitAll(tasks);

From the original 2202 milliseconds we were able to improve to 1687… seems we have some overhead costs, but even do it was an improvement.

Now I want to show you the “Parallel For”, a resource introduced in the .NET 4. When we have to do simple operations the results can be questioned (because some operations are so simple that does not pay the cost of divide the task among the cores).

Just to have an ideia:

static void Main(string[] args)
{
    var total = 1000000;
    var stopwatch = new Stopwatch();

    //pause to stabilize the system
    Thread.Sleep(1000);

    // normal for
    stopwatch.Start();
    for (int i = 0; i < total; i++) ;
    stopwatch.Stop();
    Console.WriteLine($"'normal for' elapsed milliseconds: {stopwatch.ElapsedMilliseconds}");

    //pause to stabilize the system
    Thread.Sleep(1000);

    stopwatch.Reset();

    // parallel for
    stopwatch.Start();
    Parallel.For(0, total, i => { });
    stopwatch.Stop();
    Console.WriteLine($"'parallel for' elapsed milliseconds: {stopwatch.ElapsedMilliseconds}");

    Console.ReadLine();
}

This code jus run empty for commands, and here are the results:

Metaphors:

One painter can took almost twice times to paint 300m² than two painter. But what about 1m²? Probably the second one will disturb more than help!

And in some cases there is no possible improve the process, for instance, 9 pregnant women can’t do a baby in one month.

But lets apply it to our Factorial scenario:

Parallel.For(0, timesToCalculate, (i) => {
    GetFactorial(number);
});

Now, lets see the new results:

How cool was that!? We manage to drop the time from 2202 milliseconds to 909 🙂

You probable are asking yourself what will happen if mix the parallel for with the Tasks? To be honesty, that does not make sense, because it will be thread over thread. Threads has overheads costs, thinks like sync results, monitoring, memory managements… so, use it wisely 😉

But it is really easy to apply parallelism using .NET. The framework can handle and calculate how to use the hardware properly. And if you have just one core, there is no error or problem.

And you can control it easy as well, for instance, using “parallel for” is possible set the max amount of core it will be used.

Also, you can spend some time taking a look at PLINQ.

Enjoy it.

GitHub

Spaki.

With more than 15 years of experience developing softwares and technologies, talking about startups, trends and innovation, today my work is focused to be CTO, Software Architect, Technical Speaker, Technical Consultant and Entrepreneur.

From Brazil, currently lives in Portugal working at https://www.farfetch.com as Software Architect, besides to keep projects in Brazil, like http://www.almocando.com.br/

Share

346 thoughts on “Taking Advantage of Parallelism in .NET”

  1. Pingback: Google
  2. Pingback: dual vibrator
  3. Pingback: amazon offers
  4. Pingback: دليلي
  5. Pingback: termeh
  6. Pingback: Belize inn
  7. Pingback: 脱毛
  8. Pingback: nebbia leginy
  9. Pingback: گوگل adwords
  10. Pingback: PHP login script
  11. Pingback: کولر مسجد
  12. Pingback: persian tar
  13. Pingback: free resume
  14. Pingback: سیستم cctv
  15. Pingback: خرید vpn
  16. Pingback: خرید vpn
  17. Pingback: سیستم cctv
  18. Pingback: خرید vpn
  19. Pingback: love tips
  20. Pingback: خرید vpn
  21. Pingback: خرید طلا
  22. Pingback: سیستم cctv
  23. Pingback: فروش طلا
  24. Pingback: IPhone bulk
  25. Pingback: سیستم cctv
  26. Pingback: خرید طلا
  27. Pingback: خرید vpn
  28. Pingback: gratis inserate
  29. Pingback: خرید vpn
  30. Pingback: p spot stimulation
  31. Pingback: سیستم cctv
  32. Pingback: خرید vpn
  33. Pingback: hp printer drivers
  34. Pingback: rotating dildo
  35. Pingback: sex toys orgasm
  36. Pingback: clitoral vibrators
  37. Pingback: sheet
  38. Pingback: 50 shades vibrator
  39. Pingback: beauty
  40. Pingback: credit repair
  41. Pingback: خرید طلا
  42. Pingback: pets mega malls
  43. Pingback: rampant rabbit
  44. Pingback: nipple play
  45. Pingback: خرید طلا
  46. Pingback: ساب زنی
  47. Pingback: massive dildo
  48. Pingback: dani daniels
  49. Pingback: سیستم cctv
  50. Pingback: خرید vpn
  51. Pingback: خرید طلا
  52. Pingback: dildo
  53. Pingback: best penis pump
  54. Pingback: سیستم cctv
  55. Pingback: olcsó tanfolyam
  56. Pingback: look at this now
  57. Pingback: Lastminute
  58. Pingback: glass toy
  59. Pingback: sex toy haul
  60. Pingback: mom sexually
  61. Pingback: خرید طلا
  62. Pingback: سیستم cctv
  63. Pingback: masturbator lube
  64. Pingback: hydroquinone
  65. Pingback: lubricant review
  66. Pingback: hp drivers
  67. Pingback: iphone repair
  68. Pingback: orgasm
  69. Pingback: mini massager
  70. Pingback: خرید vpn
  71. Pingback: organic besan
  72. Pingback: realistic vibe
  73. Pingback: bahis siteleri
  74. Pingback: kona coffee beans
  75. Pingback: miniclip
  76. Pingback: bahis siteleri
  77. Pingback: flying shark
  78. Pingback: bahis siteleri
  79. Pingback: bet online
  80. Pingback: bahis siteleri
  81. Pingback: bahis siteleri
  82. Pingback: bahis siteleri
  83. Pingback: goldenbah's
  84. Pingback: penis size
  85. Pingback: bondage -bitcoin
  86. Pingback: clit vibator
  87. Pingback: Morgellons Cure
  88. Pingback: bunny vibrator
  89. Pingback: clash royale hack
  90. Pingback: imoti
  91. Pingback: shooting jackets
  92. Pingback: PHP Scripts
  93. Pingback: Sandskädda
  94. Pingback: pegging sex toys
  95. Pingback: solaray
  96. Pingback: life like dildo
  97. Pingback: moms bundle
  98. Pingback: Proper Order
  99. Pingback: join illuminati
  100. Pingback: sex funiya
  101. Pingback: matka result
  102. Pingback: jageze
  103. Pingback: free dating site
  104. Pingback: Get free backlinks
  105. Pingback: payday
  106. Pingback: cursos gratis
  107. Pingback: Equipment
  108. Pingback: garudaqq android
  109. Pingback: p3d coin
  110. Pingback: hydration
  111. Pingback: Phone Repairs
  112. Pingback: Instagram unfollow
  113. Pingback: psychic
  114. Pingback: psychic
  115. Pingback: Computer City
  116. Pingback: Vancouver Escorts
  117. Pingback: Africans online
  118. Pingback: gps tracker
  119. Pingback: drivers
  120. Pingback: sex toy experience
  121. Pingback: respuestas ceneval
  122. Pingback: golf lessons
  123. Pingback: prayer
  124. Pingback: brazilian hair
  125. Pingback: sex life
  126. Pingback: remy hair
  127. Pingback: Indian hair
  128. Pingback: malaysian hair
  129. Pingback: better health ways
  130. Pingback: peruvian hair
  131. Pingback: sexier heat up
  132. Pingback: Vibrator Bullet
  133. Pingback: Shower
  134. Pingback: fantasy novel
  135. Pingback: first dildo
  136. Pingback: travel news
  137. Pingback: nasal
  138. Pingback: prazdniki zavtra
  139. Pingback: Cheap project app
  140. Pingback: pubg tshirt
  141. Pingback: dialing codes
  142. Pingback: tracing video
  143. Pingback: christ movie
  144. Pingback: Atorvastatin
  145. Pingback: Hydroquinone
  146. Pingback: Hydroquinone
  147. Pingback: sportotobet
  148. Pingback: Cryptocurrency
  149. Pingback: FRP floor cover
  150. Pingback: mermaid series
  151. Pingback: satisfyer pro
  152. Pingback: hosting
  153. Pingback: Americab.net
  154. Pingback: Online cialis
  155. Pingback: Viagra uk
  156. Pingback: Cialis prices
  157. Pingback: Generic viagra
  158. Pingback: Online cialis
  159. Pingback: ROUND
  160. Pingback: Sports news
  161. Pingback: trah_net_621
  162. Pingback: sasha grey toy
  163. Pingback: make money online
  164. Pingback: beginner anal toys

Leave a Reply