Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 比较时间-单线程与多线程的结果不同_C#_Multithreading_Single Threaded - Fatal编程技术网

C# 比较时间-单线程与多线程的结果不同

C# 比较时间-单线程与多线程的结果不同,c#,multithreading,single-threaded,C#,Multithreading,Single Threaded,我编写这段代码是为了测试多线程和单线程的速度。感谢所有的反馈!我根据收到的好评改写了大部分内容。现在它可以正常工作了(这里或那里可能有一个bug),首先测试多线程,然后取一个平均值来找到一个更准确的速度:(滚动到底部继续。) 主方法类 using System; namespace SingleAndMultiThreading { internal class Threads { private static void Main(string[] args) {

我编写这段代码是为了测试多线程和单线程的速度。感谢所有的反馈!我根据收到的好评改写了大部分内容。现在它可以正常工作了(这里或那里可能有一个bug),首先测试多线程,然后取一个平均值来找到一个更准确的速度:(滚动到底部继续。)

主方法类

using System;

namespace SingleAndMultiThreading
{
internal class Threads
{
    private static void Main(string[] args)
    {

        long numOfObjCreated;
        int numberOfTests;

        while (true)
        {
            try
            {
                Console.Write("Number of objects to create: ");
                numOfObjCreated = Convert.ToInt64(Console.ReadLine());
                break;
            }
            catch (Exception)
            {
                Console.WriteLine("Invalid input.");
            }
        }


        while (true)
        {
            try
            {
                Console.Write("Number of tests to run: ");
                numberOfTests = Convert.ToInt32(Console.ReadLine());
                break;
            }
            catch (Exception)
            {
                Console.WriteLine("Invalid input.");
            }
        }


        CalculateResults(numOfObjCreated, numberOfTests);

        Console.ReadKey();

    }


    private static void CalculateResults(long numOfObjCreated, int numberOfTests)
    {
        double totalPercentages = 0;
        for (var i = 0; i < numberOfTests; i++)
        {
            totalPercentages += CompleteTests(numOfObjCreated);
        }

        var accuracy = totalPercentages / numberOfTests;

        if ((int)accuracy == 0)
        {
            Console.WriteLine("\nIn this case, neither single threading or multithreading is faster.\n" +
                              "They both run equally well under these conditions.\n");
            return;
        }

        if (accuracy < 0)
        {
            Console.WriteLine("\nIn this case with {0} objects being created, single threading is faster!\n",
                string.Format("{0:#,###0}", numOfObjCreated));
            return;
        }

        Console.WriteLine("\nFrom {0} test(s), {1}% was the average percentage of increased speed in multithreading.\n",
            string.Format("{0:#,###0}", numberOfTests), string.Format("{0:#,###0}", accuracy));
    }

    private static double CompleteTests(long numOfObjCreated)
    {
        Console.WriteLine("Computing...");

        var numOfCores = Environment.ProcessorCount;

        var timeForMultiThread = MultiThread.Run(numOfObjCreated, numOfCores);
        var timeForSingleThread = SingleThread.Run(numOfObjCreated);

        var percentFaster = ((timeForSingleThread / timeForMultiThread) * 100) - 100;

        //note: .NET does its part in assigning a certian thread to its own core

        Console.WriteLine("Using all {0} cores, creating {1} objects is {2}% faster.",
            numOfCores, string.Format("{0:#,###0}", numOfObjCreated), string.Format("{0:#,###0}", percentFaster));

        return percentFaster;
    }
}
}
使用系统;
名称空间单线程和多线程
{
内部类线程
{
私有静态void Main(字符串[]args)
{
长numOfObjCreated;
整数测试;
while(true)
{
尝试
{
Write(“要创建的对象数:”);
numOfObjCreated=Convert.ToInt64(Console.ReadLine());
打破
}
捕获(例外)
{
Console.WriteLine(“无效输入”);
}
}
while(true)
{
尝试
{
Write(“要运行的测试数:”);
numberOfTests=Convert.ToInt32(Console.ReadLine());
打破
}
捕获(例外)
{
Console.WriteLine(“无效输入”);
}
}
计算结果(numOfObjCreated,numberOfTests);
Console.ReadKey();
}
私有静态void CalculateResults(长numobjcreated,int numberOfTests)
{
双重总百分比=0;
对于(var i=0;i
单线程类

using System;
using System.Diagnostics;

namespace SingleAndMultiThreading
{
internal class SingleThread
{
    public static double Run(long numOfObjCreated)
    {
        var watch = new Stopwatch();

        watch.Start();

        for (long i = 0; i < numOfObjCreated; i++)
        {
            new object();
        }

        watch.Stop();

        var totalTime = watch.ElapsedTicks;

        Console.WriteLine("The time to create {0} objects with 1 thread is: {1} ticks.",
            string.Format("{0:#,###0}", numOfObjCreated), string.Format("{0:#,###0}", totalTime));

        return totalTime;

    }
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;

namespace SingleAndMultiThreading
{
internal class MultiThread
{
    public static double Run(long numOfObjCreated, int numOfCores)
    {
        var watch = new Stopwatch();

        var workerObject = new Worker(numOfObjCreated / numOfCores);

        var listOfThreads = new List<Thread>();


        for (long k = 0; k < numOfCores; k++)
        {
            var workerThread = new Thread(workerObject.DoWork);
            listOfThreads.Add(workerThread);
        }

        watch.Start();
        foreach (var thread in listOfThreads)
        {
            thread.Start();
        }

        byte countOfCompletedThreads = 0;

        while (true)
        {
            foreach (var thread in listOfThreads)
                if (!thread.IsAlive)
                    countOfCompletedThreads++;

            if (countOfCompletedThreads == numOfCores)
                break;
            countOfCompletedThreads = 0;

        }

        watch.Stop();

        var totalTime = watch.ElapsedTicks;

        Console.WriteLine("The time to create {0} objects utilizing all {1} cores is: {2} ticks.",
            string.Format("{0:#,###0}", numOfObjCreated), numOfCores, string.Format("{0:#,###0}", totalTime));

        return totalTime;

    }
}
}
使用系统;
使用系统诊断;
名称空间单线程和多线程
{
内部类单线程
{
公共静态双运行(长numOfObjCreated)
{
var watch=新秒表();
watch.Start();
for(长i=0;i
多线程类

using System;
using System.Diagnostics;

namespace SingleAndMultiThreading
{
internal class SingleThread
{
    public static double Run(long numOfObjCreated)
    {
        var watch = new Stopwatch();

        watch.Start();

        for (long i = 0; i < numOfObjCreated; i++)
        {
            new object();
        }

        watch.Stop();

        var totalTime = watch.ElapsedTicks;

        Console.WriteLine("The time to create {0} objects with 1 thread is: {1} ticks.",
            string.Format("{0:#,###0}", numOfObjCreated), string.Format("{0:#,###0}", totalTime));

        return totalTime;

    }
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;

namespace SingleAndMultiThreading
{
internal class MultiThread
{
    public static double Run(long numOfObjCreated, int numOfCores)
    {
        var watch = new Stopwatch();

        var workerObject = new Worker(numOfObjCreated / numOfCores);

        var listOfThreads = new List<Thread>();


        for (long k = 0; k < numOfCores; k++)
        {
            var workerThread = new Thread(workerObject.DoWork);
            listOfThreads.Add(workerThread);
        }

        watch.Start();
        foreach (var thread in listOfThreads)
        {
            thread.Start();
        }

        byte countOfCompletedThreads = 0;

        while (true)
        {
            foreach (var thread in listOfThreads)
                if (!thread.IsAlive)
                    countOfCompletedThreads++;

            if (countOfCompletedThreads == numOfCores)
                break;
            countOfCompletedThreads = 0;

        }

        watch.Stop();

        var totalTime = watch.ElapsedTicks;

        Console.WriteLine("The time to create {0} objects utilizing all {1} cores is: {2} ticks.",
            string.Format("{0:#,###0}", numOfObjCreated), numOfCores, string.Format("{0:#,###0}", totalTime));

        return totalTime;

    }
}
}
使用系统;
使用System.Collections.Generic;
使用系统诊断;
使用系统线程;
名称空间单线程和多线程
{
内部类多线程
{
公共静态双运行(长numOfObjCreated,int numOfCores)
{
var watch=新秒表();
var workerObject=新工作程序(numOfObjCreated/numOfCores);
var listOfThreads=新列表();
对于(长k=0;k
工人阶级

namespace SingleAndMultiThreading
{
public class Worker
{
    private readonly long _numOfObjToCreate;
    public bool IsDone;

    public Worker(long numOfObjToCreate)
    {
        _numOfObjToCreate = numOfObjToCreate;
    }

    public void DoWork()
    {
        for (long i = 0; i < _numOfObjToCreate; i++)
        {
            new object();
        }

        IsDone = true;
    }
}
}
名称空间单线程和多线程
{
公社工人
{
私有只读long_numobjtocreate;
公共广播电台;
公共工作者(长Numofobjtocrate)
{
_numobjtocreate=numobjtocreate;
}
公共工作
{
对于(长i=0;i<\u numobjtocrate;i++)
{
新对象();
}
IsDone=true;
}
}
}
这段代码的输出有点太长,无法发布(我敦促您复制并粘贴到自己的IDE中,这真的很吸引人)。我猜大家公认的答案是,每次测试的结果都不一样,这是由于CPU调度、ASLR等其他或次要问题造成的。除了运行该程序的VisualStudio和优先级之外,还有不止一件事情正在发生