3

In C#, how to check if current CPU and OS support AVX instruction set?

I need to choose which native DLL to load, SSE2 or AVX.

Soonts
  • 20,079
  • 9
  • 57
  • 130

1 Answers1

8

Best way is to pinvoke GetEnabledXStateFeatures(), it ensures that both the processor and the OS support AVX:

public static bool HasAvxSupport() {
    try {
        return (GetEnabledXStateFeatures() & 4) != 0;
    }
    catch {
        return false;
    }
}

[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern long GetEnabledXStateFeatures();

No decent way to distinguish between AVX and AVX2 btw, luckily you didn't ask for that.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536