是否可以在 Rust 中使用 SIMD 指令?

Is it possible to use SIMD instructions in Rust?

在C/C++中,您可以对SIMD(例如AVX 和AVX2)指令使用内部函数。有没有办法在 Rust 中使用 SIMD?

答案是肯定的,但要注意:

  • 它在 x86 和 x86_64 through the core::arch module, reexported as std::arch.
  • 稳定版上可用
  • 其他 CPU 目前需要使用夜间编译器。
  • 并非所有指令都可以通过 core::arch 获得,在这种情况下,内联汇编是必要的,这也需要夜间编译器。

std::arch 模块仅提供 CPU 指令作为内在函数,并且需要使用 unsafe 块以及包含这些指令的函数的特定 feature正确对齐参数。 std::arch 的文档是编译时和 运行 时检测 CPU 特性的良好起点。

如文档中所述,更高级别的 API 可能会在将来的某个时候在 std::simd(可能 core::simd)下可用; the stdsimd crate:

中提供预览

Ergonomics

It's important to note that using the arch module is not the easiest thing in the world, so if you're curious to try it out you may want to brace yourself for some wordiness!

The primary purpose of this module is to enable stable crates on crates.io to build up much more ergonomic abstractions which end up using SIMD under the hood. Over time these abstractions may also move into the standard library itself, but for now this module is tasked with providing the bare minimum necessary to use vendor intrinsics on stable Rust.

注意:您也可以在图书馆中使用 FFI 来 link;例如 Shepmaster's cupid crate 使用这样的策略在 运行 时间访问 cpu 特征。