设置 ProcessorAffinity 和 TPL [英] Setting ProcessorAffinity and the TPL

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

问题描述

如果我像这样为我的进程设置处理器关联:

If I set my processor affinity for my process like so:

var me = Process.GetCurrentProcess();
me.ProcessorAffinity = (IntPtr) processorAffinityMask;

...,TPL 会尊重它的所有工作吗?也就是说,是否有任何默认调度程序可以将工作推送到我给定的掩码不允许的处理器?有没有测试可以证明这一点?

..., will the TPL honor that for all of its work? That is, are there any got-ya's with the default scheduler that would push work to a processor not allowed by my given mask? Is there a test that will prove this?

推荐答案

是的,TPL 将遵守您指定的关联掩码.

Yes the TPL will honor the affinity mask that you specify.

尊重它的唯一方法是明确地去改变亲和力,但它没有这样做.

The only way it could not honor it is to explicitly go and change the affinity, and it does not do that.

虽然创建一个测试来执行 TPL 中所有可能的代码路径是非常不可行的,但您当然可以设置一个可以从许多可用内核中受益的测试,将关联掩码设置为 1 个 CPU,并通过任务管理器进行观察亲和性永远不会改变,CPU 利用率永远不会超过 1/N,其中 N 是存在的内核数量.

While it would be highly unfeasible to create a test that would exercise every possible code path in TPL, you can certainly setup a test that would benefit from many available cores, set the affinity mask to 1 CPU, and observe through Task Manager that the affinity never changes and CPU utilization is never more than 1/N where N is the # of cores present.

您还可以将该测试扩展为具有 M 个内核的亲和性,并观察 CPU 利用率 <= M/N.也可以直接在任务管理器中观察亲和度没有变化.

You could also expand that test to have an affinity of M cores, and observe that CPU utilization <= M/N. You can also directly observe that the affinity does not change in Task Manager.

一个合适的测试应该是每次迭代需要大量时间并提供许多独立的工作单元,例如计算第一个素数 > N,其中 N 很大,并在目标素数数组上使用 Parallel.Foreach.阵列大小应明显大于现有内核数.

A suitable test would be one that requires significant time per iteration and offers many independent units of work, e.g. calculate the first prime > N where N is large and use Parallel.Foreach on an array of target primes. The array size should be significantly greater than the number of cores present.

顺便提一下,显式设置 CPU 关联性很少是一个好主意.好奇你的用例是什么.

On a side note, it is seldom a good idea to explicitly set the CPU affinity. Curious what your use case is.

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

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