Windows: Set processor affinity

From time to time, one might want to start a process on one or more dedicated CPU/cores.

The task manager has this ability in the process view, but this only changes runtime, and you have to do this every time you start that process.

The quick solution, is to use START. From Windows 2003 Server and Windows Vista, this command has the /AFFINITY option, that will give you a persistent way of dictating the CPU affinity.

The help from START /? says this:

AFFINITY The new application will have the specified processor
affinity mask, expressed as a hexadecimal number.

The question is, how to apply this?

Well, the cores have the following hex numbers:

  1. x01

  2. x02

  3. x04

  4. x08

  5. x10

  6. x20

  7. x40

  8. x80

To start a process on CPU 1 and 2, you will have to use the hex number 3 (1+2), for 1, 2, 3 and 4 the hex number f (1+2+4+8).

Like this:

START /AFFINITY f mycommand.exe

To easily calculate these hex numbers, I use a Perl one-liner like this:

$ perl -e 'map{$hex += 2**($_-1)} @ARGV; printf "%x\n", $hex;' 1 3 5 7


  1. Unfortunately, by the time the user gets to the desktop, most processes are started, making this pretty useless.

    you need to reset the affinity of existing processes programatically so that the windows processes all get limited to 1-2 cores rather than being able to take up your whole computer -- temporarily, users have a window to actually limit windows from sucking up their entire computer -- it was joked that when 2nd cores first came out, that the 2nd process would be used just to run all the windows background crap -- unfortunately not only is that no joke now, but 1 core often isn't enough. But if you have a 2 core machine I would limit the windows processes that are not in line with user-io (like file indexing, backups) to 1 core, even on a 4-6 core cpu, limiting those background tasks to 1 core will prevent them from swamping your system with io/requests, (disk or network) which are not currently not controlled by setting priority. At least by setting them all to 1 cpu, they will starve each other for cpu AND more importantly in some cases -- not flush your application's cache with system processes being swapped in.

  2. @Astara: We have never used this kind of trick to prevent users from getting CPU resources, but we do use it all the time to provide a better utilization of the resources.

    We do a lot of scientific calculations, and setting affinity for a process, constraining it to a specific CPU core, will give a slightly better performance, as the process will not "hop" for core to core, flushing memory segments etc.

    A lot of SMP aware software will in fact try to do this automatic. Home brew software tend to ignore this, as the amount of time spent on developing such a framework are rather spent on doing the scientific algorithms.