The key words to look for would be "CPU detection" or "CPU identification".
For distinguishing between architectures, like ARM vs Intel (x86), the question is moot. At the level of assembly, you had to pick an architecture to decide what instructions to code in the first place. For instance, if you wanted to add two numbers, did you write add eax, ebx
(assembling to the bytes 01 d8
), or did you write add x0, x1, x2
(assembling to 20 00 02 8b
)? In the former case, you're writing for x86. In order to get to your supposed architecture detection code in the first place, you had to execute a lot of previous instructions that would only run on x86, so by the time you get there, you already know the answer. In the latter case you're writing for ARM (ARM64).
(Technically the same sequence of bytes will do something on both architectures; but on the other one, it surely won't be what you want. Usually the assembler/linker would tag your executable with the correct architecture, and if it doesn't match the machine where it's being run, the operating system will refuse to execute it.)
For distinguishing between CPUs of the same architecture, you first have to decide which architecture that is, as the methods will likely be very different. Very generally, there is usually some special instruction which returns information about the CPU. On x86 you mainly use cpuid
, on ARM64 there are various system registers accessed with mrs
, and so on. For how they work, and how to interpret the results, you have to consult the instruction set reference for that architecture.
For x86 in particular, there have been so many different x86 CPUs released over the years (between Intel, AMD, and other now-defunct competitors) that detection can be very complicated, depending how far back you want to go. (For instance, the cpuid
instruction hasn't always existed, so the issue distinguishing between older CPUs, say pre-2000, could fill a long article.) Nowadays, there's the extra issue that your program may not even be running on x86 hardware, but may instead be in a VM with some other CPU that emulates x86.
For most purposes, the general question of "how do I tell which kind of CPU" is not really the right question to ask. Rather, identify the particular CPU feature you are interested in using (e.g. AVX instructions, enhanced rep movsb
, etc), and then ask "how do I tell whether this CPU supports it"? Then usually there is a simple answer, e.g. "load 0x1234 into eax
, execute CPUID, and check bit 7 of ecx
" (made up example). Beyond that, there's no point in writing a lot of code to tell the difference between a Brandy Lake i8-1234U at 2035 MHz or a Vodka Lake i9-9876Z at 3107 MHz; in principle you could find out which one you are running on, but as a programmer you have no actual reason to care.