7

I would like to check if SSE4 or AVX is supported at runtime, so that my program may take advantage of processor specific instructions without creating a binary for each processor.

If I could determine it at runtime, I could use an interface and switch between different instruction sets.

Paul R
  • 208,748
  • 37
  • 389
  • 560
Thomas
  • 6,032
  • 6
  • 41
  • 79
  • 1
    Including which compilers and platforms you will be using would be a good idea. – Ulfalizer Mar 21 '15 at 00:36
  • 2
    http://stackoverflow.com/a/7495023/4231385 probably answers your question. – cremno Mar 21 '15 at 00:40
  • 3
    Since it seems to be pretty far down on that page, `__builtin_cpu_supports()` is probably the easiest option for GCC 4.8+: https://gcc.gnu.org/onlinedocs/gcc-4.9.2/gcc/X86-Built-in-Functions.html#X86-Built-in-Functions . MSVC is bound to have something similar. They probably just use CPUID: http://en.wikipedia.org/wiki/CPUID . – Ulfalizer Mar 21 '15 at 00:45
  • 1
    some other possible duplicates: [What's the proper way to use different versions of SSE intrinsics in GCC?](http://stackoverflow.com/questions/15584983/whats-the-proper-way-to-use-different-versions-of-sse-intrinsics-in-gcc), [Have different optimizations (plain, SSE, AVX) in the same executable with C/C++](http://stackoverflow.com/questions/14408136/have-different-optimizations-plain-sse-avx-in-the-same-executable-with-c-c) http://stackoverflow.com/a/25911959/995714 – phuclv Mar 21 '15 at 02:59

2 Answers2

14

GCC has a way of doing this that starts by calling __builtin_cpu_init then calling __builtin_cpu_is and __builtin_cpu_supports to check features. https://gcc.gnu.org/onlinedocs/gcc-4.8.2/gcc/X86-Built-in-Functions.html

On x86, when using the C++ frontend, GCC supports "function multiversioning", which allows you to write multiple versions of the function, specify the target it should be used on, and let GCC take care of making sure it is called. https://gcc.gnu.org/onlinedocs/gcc-4.9.0/gcc/Function-Multiversioning.html

Tyler
  • 1,818
  • 2
  • 13
  • 22
  • 2
    Despite the fact that this question was marked a duplicate you still taught me something new and useful. This is a good example of why we should not be to hasty to mark questions as duplicates. – Z boson Mar 23 '15 at 07:57
3

On MSVC, extern int __isa_available has information about the CPU support on a MSVC build.

It is used by the vectorizer in MSVC 2013 to pick what assembly to run.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524