Search code examples
c#.netcpuaffinity

To set the affinity of CPUs using C#


I have created a window application in C#.Now I want to set the CPU affinity for this application.I may have 2 processors,4 processors,8 processors or may be more than 8 processors.

I want to set the cpu affinity using input from interface.

How can i achieve this? How can it is possible to set the affinity using Environment.ProcessorCount?


Solution

  • Try this:

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

    Here's more about it.

    ProcessorAffinity represents each processor as a bit. Bit 0 represents processor one, bit 1 represents processor two, and so on. The following table shows a subset of the possible ProcessorAffinity for a four-processor system.

    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
    

    Here's a small sample program:

    //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);
        }
    }