C# Parallel.For Example (Benchmark)

Use Parallel.For to call a method on multiple threads. Measure the performance improvement.
Parallel.For. A loop iterates over a method call many times. Sometimes, the method calls can be called in a parallel way—in any order.
When we can use parallel calls, we can speed up some programs by 4 times on a quad-core processor. This is a big improvement. We can use Parallel.For to make this optimization easier.
An example. Consider this program—we have a "values" array with 1000 integer elements. And our Example() method sums, and computes the product for, these elements.

And: The results are discarded. The Example method must be called many times—and these calls can be done in any order.

Version 1: We call Example in the Parallel.For method. Executions are performed on multiple threads.

Version 2: We run the Example method sequentially, on 1 thread. No multi-threading is done.

C# program that uses Parallel.For using System; using System.Threading.Tasks; using System.Diagnostics; using System.Linq; class Program { static int[] _values = Enumerable.Range(0, 1000).ToArray(); static void Example(int x) { // Sum all the elements in the array. int sum = 0; int product = 1; foreach (var element in _values) { sum += element; product *= element; } } static void Main() { const int max = 10; const int inner = 100000; var s1 = Stopwatch.StartNew(); for (int i = 0; i < max; i++) { Parallel.For(0, inner, Example); } s1.Stop(); var s2 = Stopwatch.StartNew(); for (int i = 0; i < max; i++) { for (int z = 0; z < inner; z++) { Example(z); } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / max).ToString("0.00 ns")); Console.Read(); } } Output 11229670.00 ns Parallel.For 46920150.00 ns for
Results. The Parallel.For version (version 1) finishes about 4 times faster than the sequential version. The computer being used has a quad-core processor.

Max: Try increasing the "max" local to 1000 or something. Then run the program and open the Task Manager.

And: The CPU (even on a quad-core system) will go to 100% (or 99%) while Parallel.For is running.

Tip: It will drop down to 25% when the sequential calls are being executed. The Parallel.For is doing work in parallel.

A summary. With Parallel.For we can do certain methods in parallel. This does not always help, but in tasks where the CPU usage is intensive, and no dependencies are present, it may help.Parallel.InvokeFor
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to