【发布时间】:2015-07-09 17:23:51
【问题描述】:
我知道有几个人问过类似的问题,但我找不到任何可以让我理解为什么它变慢的答案。
所以,为了自己理解 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循环中计算几千个加密哈希值(最后一次写入控制台),您会看到加速。 -
只是为了补充以下真正好的答案:使用线程很少会成功 - 请宁愿使用来自 TPL 的更高级别的 API,例如 Tasks,或者更好的是 PLinq 和 co。 (或者如果您真的知道自己在做什么,请继续 - 但没有冒犯,但在这种情况下,您可能想先深入了解一下)
-
运行 Visual Studio Profiler,您将看到应用程序在哪里无效。 (提示:
Console)
标签: c# multithreading