Hi guys,
In my article, I want to compare the speed of sequential processing to parallel processing in various conditions, so in one example, I want to convert the following sequential command to parallel, but after converting it to parallel, it seems that the loop is not repeated for the specified number of times. It may be necessary to use
Concurrent Collection or a "lock" statement, but this usually reduces the speed of parallel processing compared to sequential processing.
I am aware that variables are shared among multiple threads. This means that multiple threads can read from and write to this variable concurrently, which may cause race conditions and other unpredictable behavior.
I want an example (preferably a simple example) for my article that compares
for
and
Parallel.For
. This example should have the following features:
• The execution of
Parallel.For
block codes should be faster than the execution of
for
block codes.
• Using a flag, a variable, or other mechanisms, ensure that the
Parallel.For
loop is executed the predefined number of times.
I use the following tools:
• .NET Framework 4.5
• Console app
• Windows 7
Thank you for your time.
Best regards
What I have tried:
static long Counter = 0;
public static long Calcute()
{
int Total = 0;
for (int i = 0; i < 30; i++)
{
Total = 20 / 4;
Total = 20 * 4;
Total = 20 ^ 4;
Total = 20 - 4;
Total = 20 % 4;
}
Counter += 30;
return Counter;
}
Sequential:
static void Main(string[] args)
{
Stopwatch SW = new Stopwatch();
Console.ReadKey();
SW.Start();
for (int i = 0; i < 50000000; i++)
{
Calcute();
Calcute();
Calcute();
Calcute();
Calcute();
}
SW.Stop();
Console.WriteLine("Total seconds: " + SW.Elapsed.TotalSeconds + ", Counter: " + Counter);
Console.ReadKey();
}
Result (
click here to see):
Counter
value=50000000*30*5=7,500,000,000
Parallel:
static void Main(string[] args)
{
Stopwatch SW = new Stopwatch();
Console.ReadKey();
SW.Start();
Parallel.For(0, 50000000, (int i) =>
{
Calcute();
Calcute();
Calcute();
Calcute();
Calcute();
});
SW.Stop();
Console.WriteLine("Total seconds: " + SW.Elapsed.TotalSeconds + ", Counter: " + Counter);
Console.ReadKey();
}
One of the results (
click here to see):
Counter
value=50000000*30*5= different values are displayed