Hi guys,
Since I'm concerned about speed and efficiency, I began reading
Gastón C. Hillar's Professional Parallel Programming with C# book and want to rewrite my project from the ground up using the parallel programming approach.
In the following exercise, I noticed that not all steps of the parallel loop are executed while comparing the execution speed of the sequential and parallel loops.
I noticed this by analyzing the text length.
On the other hand, if I also use lock
, Parallel Programming
becomes completely pointless.
In the sequential loop, the length is always 200,000, but in the parallel loop it is variable.
Sequential loop
System.Diagnostics.Stopwatch StopWatch = new System.Diagnostics.Stopwatch();
StringBuilder SB = new StringBuilder();
Console.ReadKey();
StopWatch.Start();
for (int i = 0; i < 200000; i++)
{
SB.Append("B");
}
StopWatch.Stop();
Console.WriteLine("Total seconds: " + StopWatch.Elapsed.TotalSeconds + ", Length: " + SB.Length);
Console.ReadKey();
Result:
Click on this link to see the result
Parallel.For
System.Diagnostics.Stopwatch StopWatch = new System.Diagnostics.Stopwatch();
StringBuilder SB = new StringBuilder();
Console.ReadKey();
StopWatch.Start();
Parallel.For(0, 200000, range =>
{
SB.Append("B");
});
StopWatch.Stop();
Console.WriteLine("Total seconds: " + StopWatch.Elapsed.TotalSeconds + ", Length: " + SB.Length);
Console.ReadKey();
Results:
One of the results (click to see)
Parallel.ForEach
System.Diagnostics.Stopwatch StopWatch = new System.Diagnostics.Stopwatch();
StringBuilder SB = new StringBuilder();
Console.ReadKey();
StopWatch.Start();
Parallel.ForEach(Partitioner.Create(0, 200000, ((200000 / Environment.ProcessorCount) + 1)), range =>
{
for (int i = range.Item1; i < range.Item2; i++)
{
SB.Append("B");
}
});
StopWatch.Stop();
Console.WriteLine("Total seconds: " + StopWatch.Elapsed.TotalSeconds + ", Length: " + SB.Length);
Console.ReadKey();
Results:
One of the results (click to see)
1.What is the reason for this, and how can I know if the entire parallel loop has been implemented in the projects? Please explain with an example.
2.Also, what exactly is the concept of overhead?
I use the following tools:
•
.NET Framework 4.5
•
Console app
Thank you for your time.
Best regards
What I have tried:
I also tried
List<>
as shown below; however, the
List.Count
is once again variable. Lastly, I was unable to utilize this parallel programming because of my lack of understanding.
System.Diagnostics.Stopwatch StopWatch = new System.Diagnostics.Stopwatch();
List<object> List = new List<object>();
Console.ReadKey();
StopWatch.Start();
Parallel.For(0, 200000, range =>
{
List.Add("B");
});
StopWatch.Stop();
Console.WriteLine("Total seconds: " + StopWatch.Elapsed.TotalSeconds + ", Length: " + List.Count);
Console.ReadKey();