using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
namespace BCBlockingAccess
{
class Program
{
static int[] arr = Enumerable.Range(100000000, 100000).ToArray();
static void Main(string[] args)
{
//PLINQ 的主要用途是通过在多核计算机上以并行方式执行查询委托来加快 LINQ to Objects 查询的执行速度。
//当源集合中的每个元素的处理独立进行,各个委托之间未涉及到共享状态时,PLINQ 的性能最佳。
//在下面的示例中,queryA 可能适合于 PLINQ(假定其 Select 函数涉及大量工作)。
//queryB 可能不适合,原因是 Select 语句中没有足够的工作,并且并行化的开销将抵销大部分或全部加速。
//var queryA = from num in numberList.AsParallel()
// select ExpensiveFunction(num); //good for PLINQ
//var queryB = from num in numberList.AsParallel()
// where num % 2 > 0
// select num; //not as good for PLINQ
Utils.Measure("ping",()=>{
var mm = from a in arr.AsParallel() where a % 2 == 0 select a;//每个元素的处理独立进行
Console.WriteLine(mm.Count());
});
Utils.Measure("PLinqFunc", () =>
{
var mm = from a in arr.AsParallel() select Add(a);
Console.WriteLine("changdu"+mm.Count());
});
Utils.Measure("Sequential", () =>
{
bool[] results = new bool[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
results[i] = Utils.IsPrime(arr[i]);
}
});
Utils.Measure("LINQ", () =>
{
bool[] results = arr.
Select(x => Utils.IsPrime(x)).
ToArray();
});
Utils.Measure("PLINQ", () =>
{
bool[] results = arr.AsParallel().AsOrdered().
Select(x => Utils.IsPrime(x)).
ToArray();
});
Console.ReadKey();
}
public static int Add(int i)
{
if (i % 2 == 0)
{
return i;
}
else
{
return 0;
}
}
}
class Utils
{
public static void Measure(string name, Action func)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
func();
stopwatch.Stop();
Console.WriteLine("-------------------------");
Console.WriteLine(" " + name);
Console.WriteLine(" Time: " + stopwatch.ElapsedMilliseconds + " ms");
Console.WriteLine("-------------------------");
}
public static bool IsPrime(long x)
{
if (x <= 2) return x == 2;
if (x % 2 == 0) return false;
long sqrtx = (long)Math.Ceiling(Math.Sqrt(x));
for (long i = 3; i <= sqrtx; i++)
{
if (x % i == 0) return false;
}
return true;
}
}
}