使用C#设置CPU的亲和力 [英] To set the affinity of CPUs using C#

查看:283
本文介绍了使用C#设置CPU的亲和力的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我想使用界面输入来设置cpu亲和力。

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

我该如何实现?

推荐答案

尝试以下操作:

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

Here's more about it.

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

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

示例程序:

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

这篇关于使用C#设置CPU的亲和力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆