编写高效率程序
[!NOTE]
- 选择一组适当的算法和数据结构
- 编写出编译器能够有效优化以转换成高效可执行的源代码 (
这样理解编译器的能力和局限性是一个关键)
[!TIP] 提升程序效率方法:
- 根据最终效果修改源码(不断做出修改)
- 研究源码的汇编代码,了解运行逻辑和顺序等从而做出修改
- 使用 gcc 的高级别优化,只是这样可能会使得汇编代码变的与源码相比变化较大,调试也可能出现问题。不过,这样可以使程序效率提升一个数量级
优化编译器的能力和局限性
gcc -O1/-O2/-O3/-Og test.c -o test 这样的编译虽然可以让编译器实现优化,以此产生高效率的可执行程序。但是,这样是有后果的:
- 优化后,gdb 调试时可能会出现追踪和断点调试失败
- 编译器要检查可能遇到的各种可能情况(参数相等,内存别名使用等)
可能遇到的情况

exercise

This exercise is asking what will happen if the function swap is called with xp equal to yp.
Understanding the Function:
The function swap is intended to swap the values of the variables pointed to by xp and yp. Here’s a step-by-step breakdown of what each line does:
*xp = *xp + *yp; // x = x + y
*yp = *xp - *yp; // y = (x + y) - y = x
*xp = *xp - *yp; // x = (x + y) - x = y
This works fine when xp and yp point to different variables. However, if xp and yp point to the same variable, let’s analyze what happens:
Case when xp == yp:
If xp and yp are the same, both *xp and *yp refer to the same value, let’s call it x. Now, let’s see what happens:
- First Assignment:
*xp = *xp + *yp;- This becomes
x = x + x, soxis now2 * x.
- This becomes
- Second Assignment:
*yp = *xp - *yp;- Now,
*yp = x - x, which meansx = 2 * x - 2 * x = 0.
- Now,
- Third Assignment:
*xp = *xp - *yp;- Finally,
*xp = 0 - 0, soxremains0.
- Finally,
Conclusion:
If xp equals yp, the function will set the value of the variable (which both pointers refer to) to 0. This is because each operation modifies the same value, leading to the final result being zero.