How can I create a library that will dynamically switch between SSE, AVX, and AVX2 code paths depending on the host processor/OS? I am using Agner Fog's VCL (Vector Class Library) and compiling with GCC for Linux.
Compile multi-architecture code using Agner's Vector Class Library
752 Views Asked by Aleksandr Dubinsky AtThere are 3 best solutions below
On
The assembly instruction cpuid can give you this information at runtime. Someone has helpfully created a library based on this to just what you need.
You could create a function dispatch table, and populate it with the correct code path functions based on the results of querying using this code.
UPDATE: (answer to question in comments)
To create the different code paths in the first place, you need to compile the different code paths separately, and then link them together. For each one, you specify the architecture needed by using various values of the -march switch in your compile line.
On
The file https://github.com/vectorclass/version2/blob/master/dispatch_example2.cpp shows how to make automatic dispatching into different code versions with one namespace for each. This works on all x86 platforms.
See the section "Instruction sets and CPU dispatching" in the manual to the Vector Class Library. In that section Agner writes
Read the source code to
distpatch_example.cpp. At the start of the file you should see the commentThe file
instrset_detect.cpp. You should read the source code to this also. This is what calls CPUID.Here is a summary of some, but not all of, my questions and answers on CPU dispatchers.