如何以编程方式设置WIndows 7中所有正在运行的进程的亲缘关系?

时间:2011-10-23 12:21:43

标签: windows-7 affinity

有没有办法在Windows 7中为所有正在运行的进程设置亲和力?

我想运行一些超线程基准,我想确保它们在某个核心上单独运行。我用包装器运行它们,我想做这样的事情(伪代码):

foreach process in <list of all processes>
    set affinity to all cores but core x

set affinity of the current process to core x

run benchmark 0 on core x thread 0
run benchmark 1 on core x thread 1 

现在,我认为我知道如何设置当前进程及其子进程的亲和力,但我怎么能:

  1. 遍历所有流程?
  2. 设置其他进程的亲和力?

3 个答案:

答案 0 :(得分:3)

This project on CodeProject显示了如何枚举所有进程并更改其优先级。单行更改将对其进行调整,以便枚举所有进程并更改其亲和力。只需将SetProcessPriority更改为SetProcessAffinityMask

答案 1 :(得分:3)

这是一个执行它的电源shell脚本。如果需要,您还可以使用其他bat文件运行它。 然后在任务管理器中手动设置基准的亲和力。

run_set_affinity.bat:

powershell -executionpolicy bypass -file set_affinity.ps1 

set_affinity.ps1:

# elevate privileges if we are not running as Administrator, so we can set affinity of Windows owned processes
# source: http://superuser.com/questions/108207/how-to-run-a-powershell-script-as-administrator

param([switch]$Elevated)

function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

if ((Test-Admin) -eq $false)  {
    if ($elevated) {
        'tried to elevate to full privileges, did not work, aborting'
    } else {
        'running my self again with full privileges'
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-executionpolicy bypass -noprofile -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
    }
    exit
}
'running with full privileges'





# set affinity of all processes to CPU 3 and CPU 4
# it prints processes that it was unable to set affinity of    
# source: https://digitaljive.wordpress.com/2011/11/18/set-processor-affinity-with-powershell/

# 1 (CPU 1) 
# 2 (CPU 2) 
# 4 (CPU 3) 
# 8 (CPU 4) 
# 16 (CPU 5) 
# 32 (CPU 6) 
# 64 (CPU 7) 
# 128 (CPU 8)

$affinity = 4 + 8
'setting all processes to affinity: '+$affinity
'processes unable to set affinity of: '

$allProcesses = Get-Process * 
foreach ($process in $allProcesses) { 
    try {
        $process.ProcessorAffinity = $affinity
    }
    catch {
        $process
    }
}

答案 2 :(得分:0)

我设置了一个计划任务触发器,在启动时使用以下语法运行:

start /affinity 1 java.exe

在Windows 7上成功测试。