cpu 亲和力,只允许在特定 cpu 上处理 运行

cpu affinity, allowing only process to run on a specific cpu

我想通过

将进程绑定到特定的核心 #0(cpu 亲和力)
taskset -c 0 ./run_prog

虽然它自己的程序 运行 正在内核 #0 上运行,但操作系统可能会决定 运行 其他后台和活动进程到内核 #0。换句话说,该命令严格限制 run_prog 到核心 #0,但不会阻止其他进程到核心 #0 上的 运行,这很糟糕!

有什么方法可以编写 bash 脚本来首先阻止活动进程 运行ning 在核心 #0 上,然后 运行 该任务集命令?

我已经在对原始问题的一系列评论中讨论了这个问题,但我认为这是 "the answer to the underlying problem" 而不是对您的具体问题的具体答案,所以我们开始吧:

I've heard this question a couple of times, and it was always being asked out of a misunderstanding of how simultaneous multiprocessing works. First of all: Why do you need your process on core #0? Do you have a reason?

typically, the linux kernel is quite efficient at scheduling tasks to processors in a manner that minimizes the negative effects that either process migration or a single-core-bottleneck would bring. In fact, it's very rare to see someone actually gain performance by manually setting affinities, and that usually only happens when the userland process is closely communicating with a kernel module which for some hardware or implementation reason is inherently single-threaded and can't easily be migrated.

Your question itself shows a minor misunderstanding: Affinity means that the kernel knows that it should schedule that process on the given core. Hence, other processes will automatically be migrated away from that core and only be running there if your desired task leaves a lot of that core unused. To change the "priority" your process has in CPU allocation, just change its nice value.

The reason is performance measurement by isolating the running process. Regarding the second comment, that mean we have to rely on OS scheduler because it will not run a background process on a core which is currently utilized 100% while there are idle cores.

您要衡量的不是流程的绩效 孤立地,但进程,绑定到单个 CPU!为一个 单线程进程没问题,但想象一下你的进程可能 有多个线程——这些通常都会 运行 在不同的 核心,整体性能会高得多。一般来说,试试 只是最小化机器上的非进程工作负载(即 运行 没有 a window manager/session manager 运行ning, 停止所有不必要的 服务)并使用一个非常小的 nice 值——该度量可能是 比较准确。

另外,time命令可以让你知道一个进程有多少时间 完全花费(包括等待),占用 CPU 作为用户空间进程, 并在系统调用中占用 CPU——我认为这可能符合您的需要 够好了:)