Hacker News 中文摘要

RSS订阅

更快的asin()函数就在眼前 -- Even faster asin() was staring right at me

文章摘要

作者在优化asin()函数性能时,意外发现一个更快的实现方法。通过重新审视问题,找到了原本就存在的更优解决方案,体现了编程中保持开放思维的重要性。

文章总结

更快的asin()优化方案:Estrin多项式求值法

核心发现

作者在先前发布的Cg asin()近似算法基础上,通过应用Estrin多项式求值方案,实现了进一步的性能提升。原始算法采用霍纳法(Horner's method)进行多项式计算: cpp double p = a3 * abs_x + a2; p = p * abs_x + a1; p = p * abs_x + a0; 优化后改为: cpp const double x2 = abs_x * abs_x; const double p = (a3 * abs_x + a2) * x2 + (a1 * abs_x + a0);

技术原理

这种改写实现了: 1. 将依赖链长度从3级缩短为2级 2. 允许现代乱序CPU并行计算两个独立子表达式 3. 保持相同数学精度的前提下提升指令级并行性

基准测试结果

在多种硬件/编译器组合下的测试显示: - Intel i7-10750H:最高获得1.88倍加速(MSVC) - AMD Ryzen 9:提升幅度较小(约1.1-1.4倍) - Apple M4:仅在使用Clang时显现加速(1.11倍)

实际应用验证

在光线追踪项目PSRayTracing中: - Intel平台渲染时间从212秒缩短至206秒(3%提升) - Apple M4平台性能变化在误差范围内

作者建议

  1. 数学近似法在图形学中通常足够,但需注意精度要求
  2. 应优先使用数学公式而非查找表(LUT)
  3. 强调基准测试的重要性:"这是我看别人做得不够的地方"
  4. 建议开发者退后一步重新审视问题,往往能发现更好的解决方案

"这个系列我希望真正强调基准测试(即实际测量)的重要性。这是我看别人做得不够的地方。" —— 作者

项目代码已开源在GitHub,包含完整的基准测试实现和光线追踪集成。

(注:原文中的导航菜单、项目列表、社交媒体链接等非核心内容已省略,聚焦于技术优化方案的阐述)

评论总结

以下是评论内容的总结:

  1. 关于三角函数计算方法的讨论:
  • 有评论认为atan函数比sin函数更高效:"I think it is atan function. Sin is almost a lookup query."
  • 有人建议使用多项式预处理方法提高计算速度:"Did you try polynomial preprocessing methods...they let you compute polynomials with half the multiplications"
  1. GPU并行计算的观点:
  • 有评论指出现代GPU可能不适合指令级并行(ILP):"more ILP might not necessarily be better on a modern GPU...it uses those resources to execute several threads in parallel"
  1. 数学近似方法的历史:
  • 评论介绍了印度数学家Bhaskara在公元650年提出的近似方法:"ArcCos(x)= Π √((1-x)/(4+x))...The search for better and better approximations led Indian mathematicians to independently develop branches of differential and integral calculus"
  1. 关于代码优化的建议:
  • 有建议使用xx代替abs_xabsx:"x2 could also be x*x and not just absx * abs_x, shifting the dependencies earlier"
  • 关于constexpr的疑问:"what does constexpr do for local variables?"
  1. 小角度旋转的简化方法:
  • 评论展示了小角度旋转时可以省略三角函数计算:"rotation by small angles lets you drop trig entirely...For small α and β, just approximate"
  1. 最优近似系数的讨论:
  • 详细分析了arcsin(x)近似系数的最优化:"we can nearly double our accuracy, without modifying the code, just by optimizing for the right error metric"
  1. 编译器优化能力的质疑:
  • 对编译器优化能力的惊讶:"I'm surprised that the compiler couldn't see through this"
  1. 关于三角函数优雅性的讨论:
  • 有评论认为三角函数具有优雅性:"I happen to find trigonometry to be elegant and true...I also agree that trigonometric functions lack efficiency in software"