我知道有几个人问了类似这样的问题,但我找不到任何回答可以让我理解为什么速度会变慢。
所以,我为了自己对Visual Studio 2013中线程对象的理解制作了一个小型控制台程序。我的CPU是一颗Intel Core i7,可以使用多线程。
我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static TimeSpan MTTime;
static TimeSpan STTime;
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Console.WriteLine(Environment.NewLine + "---------------Multi Process-------------" + Environment.NewLine);
Thread th1 = new Thread(new ParameterizedThreadStart(Process));
Thread th2 = new Thread(new ParameterizedThreadStart(Process));
Thread th3 = new Thread(new ParameterizedThreadStart(Process));
Thread th4 = new Thread(new ParameterizedThreadStart(Process));
th1.Start("A");
th2.Start("B");
th3.Start("C");
th4.Start("D");
th1.Join();
th2.Join();
th3.Join();
th4.Join();
stopwatch.Stop();
MTTime = stopwatch.Elapsed ;
Console.WriteLine(Environment.NewLine + "---------------Single Process-------------" + Environment.NewLine);
stopwatch.Reset();
stopwatch.Start();
Process("A");
Process("B");
Process("C");
Process("D");
stopwatch.Stop();
STTime = stopwatch.Elapsed;
Console.Write(Environment.NewLine + Environment.NewLine + "Multi : "+ MTTime + Environment.NewLine + "Single : " + STTime);
Console.ReadKey();
}
static void Process(object procName)
{
for (int i = 0; i < 100; i++)
{
Console.Write(procName);
}
}
}
}
结果图像:
我们可以清楚地看到,多线程过程是完全随机的,而单线程则只是一个接一个地执行所有操作,但我认为这对速度没有影响。
起初,我以为我的线程比程序运行所需的进程更大,但是在更换更大的进程后,单线程仍然远远是最快的。那么,我在多线程方面是否缺少了一些概念?或者这很正常,它比较慢吗?
Process
循环中计算几千个加密哈希值(最后只需一次向控制台写入)你会发现速度更快。 - bstenzel控制台
) - Anders