如何在多个核心/处理器上分割工作

时间:2013-12-22 18:13:38

标签: c# parallel-processing task-parallel-library

我想创建一个小测试,执行一些计算,看看处理器完成它的速度有多快。例如,我想得到一台机器的CPU信息,然后像这样运行测试:

public static double SumRootN(int root)
    {
        double result = 0;
        for (int i = 1; i < 10000000; i++)
        {
            result += Math.Exp(Math.Log(i) / root);
        }
        return result;
    }

    private void buttonStart_Click(object sender, EventArgs e)
    {
        labelPhysicalProcessors.Text = "";
        labelProcessorName.Text = "";
        labelLogicalProcessors.Text = "";
        labelCores.Text = "";

        this.Cursor = Cursors.WaitCursor;

        string physicalProcessors = String.Empty;
        string processorName = String.Empty;
        string logicalProcessors = String.Empty;
        string coreCount = String.Empty;

        foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
        {
            physicalProcessors = item["NumberOfProcessors"].ToString();
            logicalProcessors = item["NumberOfLogicalProcessors"].ToString();
        }


        foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
        {
            coreCount = item["NumberOfCores"].ToString();
            processorName = item["Name"].ToString();
        }

        labelPhysicalProcessors.Text = physicalProcessors;
        labelProcessorName.Text = processorName;
        labelLogicalProcessors.Text = logicalProcessors;
        labelCores.Text = coreCount;

        var watch = Stopwatch.StartNew();


        Parallel.For(2, 20, (i) =>
        {
            var result = SumRootN(i);
            //Console.WriteLine("root {0} : {1} ", i, result);
        });


        labelTime.Text = watch.ElapsedMilliseconds.ToString() + " ms";


        this.Cursor = Cursors.Arrow;

    }

这会产生:  enter image description here

我想利用CPU上的内核和逻辑处理器的数量。我怎样才能在C#中做到这一点,即如果一个机器人有更多内核,那么我想将工作分成每个内核,这样一台具有更多内核和逻辑处理器的机器将更快地运行测试。

1 个答案:

答案 0 :(得分:1)

如果您正在构建基准测试,则应该严格控制线程。 N手动启动N个线程,其中N为Environment.ProcessorCount。甚至不使用Task设施,因为它给你的公平性保证较少。

您可能希望增加线程优先级以减少上下文切换引起的时序抖动。