gpt4 book ai didi

c# - 为什么我的多线程比单线程慢?

转载 作者:IT王子 更新时间:2023-10-29 04:06:45 26 4
gpt4 key购买 nike

我知道有几个人问过类似的问题,但我找不到任何回复可以让我理解为什么它变慢了。

因此,为了自己对 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);
}
}
}
}

结果图片:

enter image description here

我们可以清楚地看到多线程过程是完全随机的,单线程只是一个接一个地执行所有操作,但我认为这不会影响速度。

起初,我认为我的线程只是比运行程序所需的进程大,但在换成更大的进程后,单线程仍然是最快的。那么,我是否错过了多线程中的一个概念?还是速度慢是正常的?

最佳答案

请注意,Process 写入控制台(基本上什么都不做),并且输出到控制台(这里充当一种共享资源)很慢,需要与其他线程。

据我了解,您使用的并行化会产生巨大的开销,但不会提高速度,因为线程显然一直在等待其他进程完成对控制台的写入。

关于c# - 为什么我的多线程比单线程慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29960436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com