I'm attempting to parallelize a task but I'm not getting good performance. At most I'm getting 50% CPU usage.
Below is a toy example where I build a list of lists of random words, and then go through every word and string reverse it. The reversing part is what I'm trying to parallelize.
To me this looks like a CPU-bound problem, so I don't really understand why CPU usage is so low.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Papa
{
class Program
{
static void Main(string[] args)
{
// Build source
var random = new Random();
var alphabet = "abcdefghijklmnopqrstuvwxyz";
Console.WriteLine("Building data source");
var source = new List<string[]>();
foreach (var i in Enumerable.Range(0, 5000000))
{
var words = random.Next(3, 50);
var line = new List<string>();
for (var j = 0; j < words; ++j)
{
line.Add(
string.Concat(
Enumerable
.Range(0, random.Next(3, 9))
.Select(w => alphabet[random.Next(0, alphabet.Length - 1)])
)
);
}
source.Add(line.ToArray());
}
// Process source
Console.WriteLine("Processing source");
var processed = new List<string[]>();
Parallel.ForEach(
source,
() => new List<string[]>(),
(line, loop, local) =>
{
var processedLine = new List<string>();
for (var i = 0; i < line.Count(); ++i)
{
processedLine.Add(string.Concat(line[i].Reverse()));
}
local.Add(processedLine.ToArray());
return local;
},
partitionResult =>
{
lock (processed)
{
processed.AddRange(partitionResult);
}
});
}
}
}


