第 132 / 187 篇

12.4. 要点与小结

说明

本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C12-CodeOpt/summary.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。

12.4. Key Takeaways and Summary

我们这段短暂(也许有些令人沮丧)的代码优化之旅,应当向读者传达一个非常重要的信息:如果你在考虑手动优化代码,就要仔细想想哪些事情值得花时间,哪些应该交给编译器。下面是希望提升代码性能时值得考虑的几条重要建议。

Our short (and perhaps frustrating) journey into code optimization should convey one very important message to the reader: if you are thinking about manually optimizing your code, think carefully about what is worth spending your time on and what should be left to the compiler. Below are some important tips to consider when looking to improve code performance.

  • 选择好的数据结构和算法

    使用恰当的算法和数据结构是无可替代的;做不到这一点,往往是代码性能差的首要原因。例如,著名的埃拉托斯特尼筛法(Sieve of Eratosthenes)生成素数的效率,远远高于我们在 optExample 中自己设计的算法,能显著提升性能。下面的清单展示了用筛法的一种实现生成 2 到 500 万之间所有素数所需的时间:

  • Choose Good Data Structures and Algorithms

    There is no substitute for using proper algorithms and data structures; failure to do so is often the top reason for poor performance in code. For example, the famous Sieve of Eratosthenes algorithm is a much more efficient way to generate prime numbers than our custom algorithm in optExample, and yields a significant improvement in performance. The following listing shows the time needed to generate all prime numbers between 2 and 5 million using an implementation of the sieve:

1
2
3
$ gcc -o genPrimes genPrimes.c
$ ./genPrimes 5000000
Found 348513 primes (0.122245 s)

筛法只需 0.12 秒就能找出 2 到 500 万之间的所有素数,而 optExample2 在打开 -O3 优化选项时生成同样的素数需要 1.46 秒(快了 12 倍)。筛法的实现留给读者作为练习;不过应该很清楚,一开始就选择更好的算法,本可以省去好几个小时繁琐的优化工作。我们的例子说明了为什么数据结构和算法知识是计算机科学家的基础。

The sieve algorithm requires only 0.12 seconds to find all the prime numbers between 2 and 5 million, compared to the 1.46 seconds it takes optExample2 to generate the same set of primes with the -O3 optimization flags turned on (12× improvement). The implementation of the sieve algorithm is left as an exercise for the reader; however, it should be clear that choosing a better algorithm up front would have saved hours of tedious optimization effort. Our example demonstrates why a knowledge of data structures and algorithms is foundational for computer scientists.

  • 尽可能使用标准库函数

    不要重新发明轮子。如果在编程过程中你需要一个做非常标准的事情的函数(例如求绝对值,或者求一组数的最大值或最小值),先停下来查一查,这个函数是否已经是高级语言标准库的一部分。标准库中的函数经过充分测试,而且往往针对性能做过优化。例如,如果读者手动实现了自己版本的 sqrt 函数,编译器可能就不知道要自动把这个函数调用替换为 fsqrt 指令。

  • Use Standard Library Functions Whenever Possible

    Don’t reinvent the wheel. If in the course of programming you need a function that should do something very standard (e.g., find the absolute value, or find the maximum or minimum of a list of numbers), stop and check to see whether the function already exists as part of the higher-level language’s standard library. Functions in the standard libraries are well tested and tend to be optimized for performance. For example, if a reader manually implements their own version of the sqrt function, the compiler may not know to automatically replace the function call with the fsqrt instruction.

  • 根据数据而不是感觉来优化

    如果在选择了最好的数据结构和算法、并且使用了标准库函数之后,仍然需要进一步提升性能,就借助 Valgrind 这样好的代码剖析工具。优化绝不应该基于直觉。把太多精力放在自己感觉应该优化的地方(而没有数据支持这种想法),往往只会浪费时间。

  • Optimize Based on Data and Not on Feelings

    If after choosing the best data structures and algorithms and employing standard library functions, additional improvements in performance are required, enlist the help of a good code profiler like Valgrind. Optimization should never be based on gut feelings. Concentrating too much on what one feels should be optimized (without the data to back up the thought) often leads to wasted time.

  • 把复杂的代码拆分成多个函数

    与现代编译器所能达到的效果相比,手动内联代码通常不会带来可观的性能提升。相反,要让编译器更容易帮你优化。编译器更容易优化较短的代码段。把复杂的操作拆分成多个函数,既能提高代码的可读性,又能让编译器更容易优化。查一查你的编译器是否默认尝试内联,或者是否有单独的选项来尝试内联代码。让编译器去做内联,比自己手动内联要好。

  • Split Complex Code into Multiple Functions

    Manually inlining code usually does not result in a sizable performance gain over what modern compilers can achieve. Instead, make it easier for your compiler to help optimize for you. Compilers have an easier time optimizing shorter code segments. Splitting complex operations into multiple functions simultaneously increases code readability and makes it easier for a compiler to optimize. Check to see whether your compiler attempts inlining by default or has a separate flag to attempt inlining code. It is better to let your compiler perform inlining rather than manually doing it yourself.

  • 优先考虑代码的可读性

    在如今的许多应用中,可读性是第一位的。事实上,代码被阅读的次数比被编写的次数多。许多公司花费大量时间培训软件工程师,让他们以一种非常特定的方式编写代码,以最大限度地提高可读性。如果优化代码会明显损害可读性,就要看看所获得的性能提升是否值得付出这个代价。例如,如今许多编译器都有开启循环展开的优化选项。程序员应当始终使用现成的循环展开优化选项,而不是试图手动展开循环,后者可能会严重损害代码的可读性。降低代码的可读性常常会增加无意中引入缺陷的可能性,进而可能导致安全漏洞。

  • Prioritize Code Readability

    In many applications today, readability is king. The truth is that code is read more often than it is written. Many companies spend considerable time training their software engineers to write code in a very particular way to maximize readability. If optimizing your code results in a noticeable hit to code readability, it is important to check if the performance improvement obtained is worth the hit. For example, many compilers today have optimization flags that enable loop unrolling. Programmers should always use available optimization flags for loop unrolling instead of trying to manually unroll loops, which can lead to a significant hit in code readability. Reducing code readability often increases the likelihood that bugs are inadvertently introduced into code, which can lead to security vulnerabilities.

  • 关注内存使用

    程序的内存使用对其执行时间的影响,往往比它执行的指令数更大。循环交换的例子就是这一点的例证。在两种情况下,循环执行的指令数相同。然而,循环的顺序对内存访问和局部性有显著影响。在尝试优化程序时,也要记得试试 massif 和 cachegrind 这样的内存剖析工具。

  • Pay Attention to Memory Use

    A program’s memory usage often has a bigger impact on the program’s execution time than the number of instructions that it executes. The loop interchange example exemplifies this point. In both cases, the loop executes the same number of instructions. However, the ordering of the loops has a significant impact on memory access and locality. Remember to also explore memory profiling tools like massif and cachegrind when attempting to optimize a program.

  • 编译器在不断改进

    编译器开发者不断更新编译器,以便安全地执行更复杂的优化。例如,GCC 从 4.0 版开始改用静态单赋值(SSA)形式,显著改善了它的一些优化的效果。GCC 代码库的 GRAPHITE 分支实现了多面体模型(polyhedral model),让编译器能够执行更复杂的循环变换。随着编译器越来越复杂,手动优化的好处会大大减少。

  • Compilers Are Constantly Improving

    Compiler writers continually update compilers to perform more sophisticated optimizations safely. For example, GCC switched to the link: static single assignment (SSA) form starting in version 4.0, which significantly improved the effects of some of its optimizations. The GRAPHITE branch of the GCC code base implements the polyhedral model, which allows the compiler to perform more complex types of loop transformations. As compilers get more sophisticated, the benefits of manual optimization significantly reduce.