Is there a crate that finds the CPU arch at runtime?

I know that the arch can be detected using #[cfg..., however, that is compile-time. I know it's possible to find the cpu arch during runtime (e.g., it could be found in the registry if absolutely needed via the kernel32 lib for windows), so there certainly ought to be a crate that accomplishes the needed goal

Can you be more specific about what details of the cpu you're trying to discover? (i.e. Arm vs x86 you can detect reliably at compile time, presence of hardware floating point support not so much)

1 Like

x86_64, x86 (64 vs 32 bit)

Are you looking for something like the CPUID instruction? There's a crate which wraps it to let you discover processor information on an x86/x86_64 machine.

EDIT: Another option is to use the core::arch module from the standard library.

heim is using uname for unixes and GetNativeSystemInfo for Windows to get the platform information "in runtime", including the system architecture, see an example here:

1 Like

I found an easy solution:

You recognize that ARCH is set at compile time, right? It's equivalent to the cfg method.


No, I did not realize that!

Might still get you what you need though.

There are a couple different parts to your question. The ARCH is simply the type of CPU that the compiler was configured to produce code for. Because it's a compiler configuration, you can reliably detect it at compile time. If you try to run a binary produced for the wrong arch, it will almost always fail.

The "almost always" in that sentence means sometimes runtime detection is useful. For example, x86-64 processors can run 32-bit x86 code. In that case the ARCH is x86 but the processor is really 64 bit. To detect cases like this you need to resort to processor specific tricks, like the cpuid crate suggested above. (There's a similar situation with 64-bit ARM chips.)

Crates like cpuid will also enable you to detect optional features, like (on x86) AVX vector instructions. However, once you've detected them, doing anything useful with that information is kind of complex. Game devs often do this to choose the fastest version of an algorithm for the user's machine. I can't help with that one.


right—on ARM (and other architectures) it's even more involved because there is no instruction similar to CPUID permissible from user-space, so to figure out what CPU extensions are available one needs to learn this in an OS-specific way (on linux, the modern way is auxv AT_HWCAP bitfields, in the past there were some horrible solutions such as parsing /proc/cpuinfo or just try and catch SIGILL, yolo)

(as for 32/64 bit, what you really want to know is "can the OS handle 32 and/or 64-bit executables", what the CPU can do is only part useful if the OS doesn't allow running executables in a certain mode, or for example due to lack of ABI or libraries)


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.