使用C#设置CPU的亲和性

时间:2012-12-12 07:07:58

标签: c# .net cpu affinity

我在C#中创建了一个窗口应用程序。现在我想为这个应用程序设置CPU亲和力。我可能有2个处理器,4个处理器,8个处理器或者可能超过8个处理器。

我想使用interface的输入设置cpu亲和力。

我怎样才能做到这一点?如何使用Environment.ProcessorCount?

设置关联

4 个答案:

答案 0 :(得分:12)

试试这个:

Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr)2;

Here更多关于此事。

ProcessorAffinity 代表每个处理器。位0表示处理器1,位1表示处理器2,依此类推。下表显示了四处理器系统的可能 ProcessorAffinity 的子集。

Property value (in hexadecimal)  Valid processors

0x0001                           1
0x0002                           2
0x0003                           1 or 2
0x0004                           3
0x0005                           1 or 3
0x0007                           1, 2, or 3
0x000F                           1, 2, 3, or 4

这是一个小样本程序:

//TODO: manage exceptions
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Total # of processors: {0}", Environment.ProcessorCount);
        Console.WriteLine("Current processor affinity: {0}", Process.GetCurrentProcess().ProcessorAffinity);
        Console.WriteLine("*********************************");
        Console.WriteLine("Insert your selected processors, separated by comma (first CPU index is 1):");
        var input = Console.ReadLine();
        Console.WriteLine("*********************************");
        var usedProcessors = input.Split(',');

        //TODO: validate input
        int newAffinity = 0;
        foreach (var item in usedProcessors)
        {
            newAffinity = newAffinity | int.Parse(item);
            Console.WriteLine("Processor #{0} was selected for affinity.", item);
        }
        Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr)newAffinity;
        Console.WriteLine("*********************************");
        Console.WriteLine("Current processor affinity is {0}", Process.GetCurrentProcess().ProcessorAffinity);
    }
}

答案 1 :(得分:4)

Alex Filipovivi提供的示例程序似乎不正确,因为它将处理器编号OR成newAffinity而不先将它们转换为设置位。 因此,如果您输入3,4到此程序,您将获得7的亲和力掩码,即核心1,2和3!掩码应设置为12(十六进制0xC,二进制1100,其中位2和3设置,如果位0是最低有效位)。

更换

newAffinity = NewAffinity | int.Parse(item);

newAffinity = newAffinity | (1 << int.Parse(item)-1);

这是一种合理的方法。

答案 2 :(得分:2)

寻找线程亲和力的人。

public class CpuAffinity
{
    [DllImport("kernel32.dll")]
    static extern IntPtr GetCurrentThread();

    [DllImport("kernel32.dll")]
    static extern IntPtr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);

    /// <summary>
    /// Sets the current Thread to have affinity to the specified cpu/processor if the system has more than one.
    /// 
    /// Supports most systems as we use a signed int; Anything more than 31 CPU's will not be supported.
    /// </summary>
    /// <param name="cpu">The index of CPU to set.</param>
    public static void SetCurrentThreadToHaveCpuAffinityFor(int cpu)
    {
        if (cpu < 0)
        {
            throw new ArgumentOutOfRangeException("cpu");
        }

        if (Environment.ProcessorCount > 1)
        {
            var ptr = GetCurrentThread();
            SetThreadAffinityMask(ptr, new IntPtr(1 << cpu));

            Debug.WriteLine("Current Thread Of OS Id '{0}' Affinity Set for CPU #{1}.", ptr, cpu);
        }else
        {
            Debug.WriteLine("The System only has one Processor.  It is impossible to set CPU affinity for other CPU's that do not exist.");
        }
    }
}

答案 3 :(得分:1)

System.Diagnostics.Process.ProcessorAffinity

您想使用Environment.ProcessorCount做什么?用户输入验证? 无论如何,如果你想选择一个特定的处理器(#1或#2或#3 ...),创建一个像这样的位掩码:

if (userSelection <= 0 || userSelection > Environment.ProcessorCount)
{
    throw new ArgumentOutOfRangeException();
}

int bitMask = 1 << (userSelection - 1);
Process.GetCurrentProcess().ProcessorAffinity = (IntPtr)bitMask;

其中userSelection - 是一些选定的处理器。

如果您想选择多个处理器,请执行

bitMask |= 1 << (anotherUserSelection - 1);
每个用户选择