我通过设置每隔一个位为假的位数组进行枚举。
现在我想通过将它分成两个线程来加快速度。但是由于一些奇怪的原因,每个线程完成一半工作的时间需要多出 64% 的时间,我想知道为什么会这样?
这可能是由于某种 CPU 缓存效应造成的吗?我该如何正确地做到这一点?
我以前也用 lambda 表达式尝试过 8 个线程,但它总是在 ~1400 毫秒左右,但是在单线程中我总是得到 850 毫秒。此外,当我让一个线程完成所有工作时,我花了 830 毫秒。我就是不明白,有人知道这是什么原因吗?
代码:
class Program
{
static int count = 0x10000000;
static int half = count / 2;
static BitArray bitArray = new BitArray(count);
static unsafe void Main(string[] args)
{
Stopwatch sw = Stopwatch.StartNew();
#if SINGLE
for (int i = 0; i < bitArray.Count; i += 2)
bitArray.Set(i, true);
#else
Thread thread1 = new Thread(Thread1);
Thread thread2 = new Thread(Thread2);
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
#endif
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Console.ReadLine();
}
static void Thread1()
{
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < half; i += 2)
bitArray.Set(i, true);
sw.Stop();
Console.WriteLine("Thread1: {0}", sw.ElapsedMilliseconds);
}
static void Thread2()
{
Stopwatch sw = Stopwatch.StartNew();
for (int i = half; i < count; i += 2)
bitArray.Set(i, true);
sw.Stop();
Console.WriteLine("Thread2: {0}", sw.ElapsedMilliseconds);
}
}