private static int ParallelTaskLoop(List <string> names, RedBlackSearchTree strTree) { int countCPU = 4; Task <int>[] tasks = new Task <int> [countCPU]; for (var j = 0; j < countCPU; j++) { tasks[j] = Task <int> .Factory.StartNew( (object p) => { int count = 0; for (int i = (int)p; i < names.Count; i += countCPU) { if (strTree.Contains(names[i])) { count++; } } return(count); }, j); } int total = 0; for (var i = 0; i < countCPU; i++) { total += tasks[i].Result; } return(total); }
private static int SequentialLoop(List <string> names, RedBlackSearchTree strTree) { int count = 0; for (int i = 0; i < names.Count; i++) { if (strTree.Contains(names[i])) { count++; } } return(count); }
static void Main(string[] args) { List <string> nameList = new List <string>(); RedBlackSearchTree strTree = new RedBlackSearchTree(); int seed = (int)DateTime.Now.Ticks & 0x0000FFFF; random = new Random(seed); int n = 60000; var stopWatch = new Stopwatch(); for (int i = 0; i < n; i++) { string s = RandomName(20); nameList.Add(s); strTree.Insert(s); } nameList.Add(RandomName(20)); stopWatch.Start(); int count = SequentialLoop(nameList, strTree); stopWatch.Stop(); Console.WriteLine("Time in milliseconds for sequential loop: {0,6:N0} ", stopWatch.ElapsedMilliseconds); Console.WriteLine("Contains: {0,6:N0} Total: {1,6:N0}", count, nameList.Count); stopWatch.Reset(); stopWatch.Start(); count = ParallelTaskLoop(nameList, strTree); stopWatch.Stop(); Console.WriteLine("Time in milliseconds for parallel loop: {0,6:N0} ", stopWatch.ElapsedMilliseconds); Console.WriteLine("Contains: {0,6:N0} Total: {1,6:N0}", count, nameList.Count); }