Yes, modern compilers can optimize this linear search using SIMD instructions, including AVX2 or AVX-512 on CPUs like Tiger Lake or Zen 5.
For GCC, you'll need these compiler options:
# For AVX2 (widely supported):
g++ -O3 -march=native -ftree-vectorize
# Or explicitly for specific architectures:
g++ -O3 -march=tigerlake # For Tiger Lake (includes AVX-512)
g++ -O3 -march=znver4 # For Zen 4 (Zen 5 uses znver5 when available)
The key flags are:
-O3: Enables aggressive optimizations including auto-vectorization
-march=native or -march=<arch>: Enables CPU-specific instruction sets
-ftree-vectorize: Explicitly enables loop vectorization (included in -O3)
However, there are some caveats:
-
Vectorization likelihood: The compiler is more likely to vectorize if the vector is larger. For small vectors, the overhead might not be worth it.
-
Alignment: Better performance if your vector data is aligned. Consider using aligned allocators if performance is critical.
-
Verification: You can check if vectorization occurred using:
g++ -O3 -march=native -fopt-info-vec-optimized
-
Alternative approaches: For better guarantees of SIMD usage, you might consider:
- Using
std::find with execution policies (C++17): std::find(std::execution::unseq, v.begin(), v.end(), h)
- Libraries like
std::experimental::simd (C++26) or third-party libraries like Highway or xsimd
The actual vectorization depends on various factors including vector size, data alignment, and compiler heuristics. You can examine the generated assembly with -S to verify SIMD instruction usage.