using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class Program
{
static long TestForeach()
{
var stopWatch = new Stopwatch();
stopWatch.Start();
var list = new List<int>();
foreach (var i in Enumerable.Range(0, 10000))
{
list.Add(i);
}
stopWatch.Stop();
return stopWatch.ElapsedMilliseconds;
}
static long TestParallelForEach()
{
var list = new List<int>();
var stopWatch = new Stopwatch();
stopWatch.Start();
Parallel.ForEach(Enumerable.Range(0, 10000), new ParallelOptions() { MaxDegreeOfParallelism = 1000 }, i =>
{
lock (list)
{
list.Add(i);
}
});
stopWatch.Stop();
return stopWatch.ElapsedMilliseconds;
}
static long TestParallelForEachThreadSafeCollection()
{
var list = new BlockingCollection<int>();
var stopWatch = new Stopwatch();
stopWatch.Start();
Parallel.ForEach(Enumerable.Range(0, 10000), new ParallelOptions() { MaxDegreeOfParallelism = 1000 }, i =>
{
list.Add(i);
});
stopWatch.Stop();
return stopWatch.ElapsedMilliseconds;
}
static void Main(string[] args)
{
var times = new List<long>();
Console.WriteLine("■TestForeach");
Enumerable.Range(0, 1000).ToList().ForEach(i => times.Add(TestForeach()));
//Enumerable.Range(0, 1000).ToList().ForEach(i => Console.WriteLine(times[i]));
Console.WriteLine(times.Average());
times = new List<long>();
Console.WriteLine("■TestParallelForEach");
Enumerable.Range(0, 1000).ToList().ForEach(i => times.Add(TestParallelForEach()));
//Enumerable.Range(0, 1000).ToList().ForEach(i => Console.WriteLine(times[i]));
Console.WriteLine(times.Average());
times = new List<long>();
Console.WriteLine("■TestParallelForEachThreadSafeCollection");
Enumerable.Range(0, 1000).ToList().ForEach(i => times.Add(TestParallelForEachThreadSafeCollection()));
//Enumerable.Range(0, 1000).ToList().ForEach(i => Console.WriteLine(times[i]));
Console.WriteLine(times.Average());
}
}
}