进程绑核 ProcessorAffinity
进程设置CPU亲和性(Processor Affinity),本质是把进程“绑”到指定的逻辑处理器上运行。
它不是万能的,但在具体场景下效率更高。
如下图,是在48个逻辑处理器中,绑定后12个CPU。

static void Main(string[] args)
{
// 获取并显示可用的CPU核心
int coreCount = Environment.ProcessorCount;
var reader = new AppSettingsReader();
string cpubit = reader.GetValue("ProcessorAffinity", typeof(string)).ToString().Replace(" ", "");
if (cpubit.Length > coreCount)
{
cpubit = cpubit.Substring(cpubit.Length - coreCount, coreCount);
}
var currentProcess = Process.GetCurrentProcess();
if (currentProcess != null)
{
long host = Convert.ToInt64(cpubit, 2);
if (host != 0)
{
IntPtr affinityMask = (IntPtr)host;
currentProcess.ProcessorAffinity = affinityMask;
// 解析并显示启用的核心
var mask = affinityMask.ToInt64();
// 显示设置结果
Console.WriteLine($"已将进程绑定到CPU核心,位掩码: 0b{Convert.ToString(mask, 2).PadLeft(coreCount, '0')}");
Console.WriteLine($"系统总CPU核心数: {coreCount}");
Console.WriteLine("启用的CPU核心:");
for (int i = 0; i < coreCount; i++)
{
if ((mask & (1L << i)) != 0)
{
Console.WriteLine($"核心 {i}");
}
}
}
else
{
Console.WriteLine($"已将进程绑定到CPU核心,位掩码: 0b{Convert.ToString(0, 2).PadLeft(coreCount, '0')}");
Console.WriteLine($"系统总CPU核心数: {coreCount}");
}
}
for (int i = 0; i < coreCount; i++)
{
Task.Delay(5000).ContinueWith(t =>
{
while (true)
{
//Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "......" + DateTime.Now);
}
});
}
Console.ReadKey();
}




Environment.ProcessorCount(32)!=实际逻辑处理器数(48)
可能是:
·程序运行在32位进程
·被人为设置了亲和性


浙公网安备 33010602011771号