编译器与SIMD优化

优化手法总结

  1. 函数尽量写在同一个文件内
  2. 避免在 for 循环内调用外部函数
  3. 非 const 指针加上 __restrict 修饰
  4. 试着用 SOA 取代AOS
  5. 对齐到 16 或64 字节
  6. 简单的代码,不要复杂化
  7. 试试看 #pragma omp simd
  8. 循环中不变的常量挪到外面来
  9. 对小循环体用#pragma unroll
  10. -ffast-math 和-march=native

优化代码

查看预汇编代码

  • 指针别名
int func ( int * __restrict a, int * __restrict b);
  • 不优化
for (volatile int i = 0; i < 1024 ; ++i);
  • gcc ymm 支持检测flag
gcc -march=native -O3
  • 忽略指针别名
# pragma omp simd
    gcc - fopenmop -O3

# pragma GCC ivdep
   //ignire vector devlop    
  • 尽量替换 面向对象编程(oop) 的 AOS 为 面向数据编程(DOP) 的 SOA
//AOS of OOP
struct obj{
  int x, y;
}example[1024];

// SOA of DOP
struct{
  int x[1024], y[1024];
}example;

  • 数学
    • 使用std::math替代 math 如std::cos 替代 cos
    • 乘法替代除法 or gcc =ffast -math
    • 适当"()"避免四则运算对矢量化计算的干扰
    • 一些float, int, double的函数精确使用
float sqrtf(float x);
int abs(any);
double fabs(any);
float fabsf(any);
posted @ 2022-12-27 16:29  InsiApple  阅读(65)  评论(0编辑  收藏  举报