PLINQ测试结果

View Code
 1     public class PLINQ
2 {
3 static int[] arr = Enumerable.Range(654321, 101010).ToArray();
4
5 public static int _computeTimes = 0;
6
7 public static void Test ()
8 {
9 Utils.Measure("Sequential", () =>
10 {
11 bool[] results = new bool[arr.Length];
12 for (int i = 0; i < arr.Length; i++)
13 {
14 results[i] = Utils.IsPrimeInt(arr[i]);
15 }
16 });
17
18 Utils.Measure("LINQ", () =>
19 {
20 bool[] results = arr.
21 Select(x => Utils.IsPrimeInt(x)).
22 ToArray();
23 });
24
25 Utils.Measure("PLINQ", () =>
26 {
27 bool[] results = arr.AsParallel().AsOrdered().
28 Select(x => Utils.IsPrimeInt(x)).
29 ToArray();
30 });
31
32 Console.WriteLine(_computeTimes.ToString());
33 }
34 }
35
36 class Utils
37 {
38 public static void Measure ( string name, Action func )
39 {
40 Stopwatch stopwatch = new Stopwatch();
41 stopwatch.Start();
42 func();
43 stopwatch.Stop();
44 Console.WriteLine("-------------------------");
45 Console.WriteLine("" + name);
46 Console.WriteLine(" Time: " + stopwatch.ElapsedMilliseconds + " ms");
47 Console.WriteLine("-------------------------");
48
49 }
50
51 public static bool IsPrime ( long x )
52 {
53 if (x <= 2)
54 return x == 2;
55 if (x % 2 == 0)
56 return false;
57
58 long sqrtx = (long)Math.Ceiling(Math.Sqrt(x));
59 for (long i = 3; i <= sqrtx; i++)
60 {
61 if (x % i == 0)
62 return false;
63 }
64 return true;
65 }
66
67
68 public static bool IsPrimeInt ( int x )
69 {
70 if (x <= 2)
71 return x == 2;
72 if (x % 2 == 0)
73 return false;
74
75 int sqrtx = (int)Math.Ceiling(Math.Sqrt(x));
76 for (int i = 3; i <= sqrtx; i++)
77 {
78 //PLINQ._computeTimes = PLINQ._computeTimes + 1;
79 if (x % i == 0)
80 return false;
81 }
82 return true;
83 }
84
85 }

Int32整数运算:

  五百万到一千万左右 运算速度区别不大

  一千万以上PLINQ较快

Int64

  三百万以上PLINQ较快

双核四线程处理器测试

原文地址:https://www.cnblogs.com/scottgu/p/2251783.html