C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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.