我编写了两种比较性能的代码,分别是Methode #1和Methode #2。Methode #1使用for循环,而Methode #2使用Parallel.Invoke。在第二种情况下运行非常缓慢。我不明白为什么会这样发生?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using Mpir.NET;
using System.Runtime.Serialization;
using System.Diagnostics;
namespace ConsoleApplication4
{
class Program
{
public class numbers
{
public numbers(mpz_t p, mpz_t q)
{
this.q = q;
this.p = p;
}
mpz_t q;
mpz_t p;
};
static void Main(string[] args)
{
Int32 arraySize = 400;
ConcurrentBag<numbers> pairsCB = new ConcurrentBag<numbers>();
ConcurrentBag<Action> cbTasks = new ConcurrentBag<Action>();
HashSet<numbers> uniqueCB = new HashSet<numbers>(pairsCB.ToArray());
mpz_t[] numbersArray = new mpz_t[arraySize];
for (Int32 i = 0; i < arraySize; i++)
{
numbersArray[i] = i*i+i+1;
}
//Methode #1
Stopwatch stopwatch1 = new Stopwatch();
stopwatch1.Start();
for (Int32 j = 0; j < arraySize; j++)
{
checkDivisible(numbersArray[j], pairsCB);
}
uniqueCB = new HashSet<numbers>(pairsCB.ToArray());
stopwatch1.Stop();
Console.WriteLine("Methode Count Unique Pairs Count:{0}\tTime elapsed:{1}", uniqueCB.Count(), stopwatch1.Elapsed);
//Methode #2
Stopwatch stopwatch2 = new Stopwatch();
stopwatch2.Start();
pairsCB = new ConcurrentBag<numbers>();
for(Int32 j = 0; j < arraySize; j++)
{
mpz_t value = numbersArray[j];
cbTasks.Add(new Action(() => checkDivisible(value, pairsCB)));
}
Action[] tasks = cbTasks.ToArray();
Parallel.Invoke(tasks);
stopwatch2.Stop();
Console.WriteLine("Methode Count Unique Pairs Count:{0}\tTime elapsed:{1}", uniqueCB.Count(), stopwatch2.Elapsed);
Console.ReadKey();
}
private static void checkDivisible(mpz_t n, ConcurrentBag<numbers> pq)
{
mpz_t p = 1;
mpz_t q = 1;
for (Int32 i = 2; i < n; i++)
{
if (n % i == 0)
{
q = i;
p = n / i;
pq.Add(new numbers(p, q));
}
}
}
}
}
numbers
数组,并在最后合并它们 - 这本质上就是任何map/reduce算法中的“reduce”步骤。 - Panagiotis Kanavos