I know a couple of people asked a question similar to this, but I can’t find any response that would make me understand why it's slower.
So, I made a little console program for my own understanding of the threading object in Visual Studio 2013. My CPU is an Intel Core i7 that supply can use multiple threading.
My code:
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);
}
}
}
}
Result image:
We can clearly see that the multi-treading process is total random and the single one just do all presses on after the other, but I don't think this have an impact on the speed.
At first, I thought my thread was just bigger than the process needed for running the program, but after changing for a bigger process the single treading still was still the fastest in a big way. So, do i miss a concept in multi-threading? Or it normal that is slower?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…