【发布时间】:2018-02-16 07:19:13
【问题描述】:
我写了一个代码,它以单线程和多线程方式执行求和函数,如下所示:
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ParallelFor
{
class Program
{
static void Main()
{
Console.WriteLine("Program started");
var step_time = Stopwatch.StartNew();
step_time.Start();
double R1 = 0.0;
double R2 = 0.0;
double R3 = 0.0;
var t1 = new Thread(() => TestCounter(2000, ref R1, 1));
var t2 = new Thread(() => TestCounter(2000, ref R2, 2));
var t3 = new Thread(() => TestCounter(2000, ref R3, 3));
t1.Start();
t2.Start();
t3.Start();
do
{
} while (t1.IsAlive == true || t2.IsAlive == true || t3.IsAlive == true);
Console.WriteLine("inside R1: {0}", R1);
Console.WriteLine("inside R2: {0}", R2);
Console.WriteLine("inside R3: {0}", R3);
Console.WriteLine("Program finished");
step_time.Stop();
Console.WriteLine("multi-thread last {0} (MilSec)\n", step_time.ElapsedMilliseconds);
step_time.Reset();
step_time.Start();
R1 = 0.0;
R2 = 0.0;
R3 = 0.0;
TestCounter(2000, ref R1, 1);
TestCounter(2000, ref R2, 2);
TestCounter(2000, ref R3, 3);
Console.WriteLine("inside R1: {0}", R1);
Console.WriteLine("inside R2: {0}", R2);
Console.WriteLine("inside R3: {0}", R3);
step_time.Stop();
Console.WriteLine("single thread last {0} (MilSec)\n", step_time.ElapsedMilliseconds);
Console.ReadLine();
}
static void TestCounter(int counter, ref double result, int No)
{
for (int i = 0; i < counter + 1; i++)
for (int j = 0; j < counter; j++)
for (int k = 0; k < counter; k++)
result += (double)i;
}
}
}
我发现单线程部分,最后更短! (我用 counter=10000 运行代码,结果是一样的!) 为什么单线程解析速度更快?!?!
【问题讨论】:
-
你不应该把线程的开始算作并行持续时间的一部分...
-
首先,您不应该使用 while
Thread.IsAlive循环,而应使用Thread.Join或其他更好的方法来等待所有线程完成。其次,您在什么 CPU/硬件上运行它,这对并行线程性能很重要。
标签: c# multithreading