TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Tips for Optimizing C/C++ Code

9 点作者 chorola大约 11 年前

2 条评论

yoklov大约 11 年前
There&#x27;s some good and bad advice here.<p>Avoiding (or at least thinking about) branches, avoiding mallocs, and simplifying equations out by hand before you code them are all hugely worthwhile. Thinking about the memory usage access patterns of your program is a must if you work in realtime simulations. (Simplifying equations is enormously important, and I&#x27;m glad to see it mentioned because most people assume that the compiler can do it for them, which in most cases it cannot).<p>OTOH much of this advice won&#x27;t make any difference other than making you code harder to read. Using local variables won&#x27;t increase register pressure compared to not using a variable for that computation. Very few compilers will actually generate temporary objects for `Vec3 res = Vec3(a, b, c) + Vec3(d, e, f) + Vec3(h, i, j)`. As I understand it, using memset vs letting the compiler zero initialize an array of classes is unnecessary unless you compile with `-fno-strict-aliasing` or similar.<p>For small programs, rolling your own STL data structures isn&#x27;t the worst advice, especially given that his target audience seems to be students (I work in gamedev, and I wouldn&#x27;t want to work with someone who couldn&#x27;t code up a STL-like templated vector, exception safety aside). Neither is avoiding templates (at least, before you can tell by looking what kind of code a complex template will expand to).<p>Anyway, for better, more thorough, and more actionable advice, there&#x27;s always [Agner Fog&#x27;s excellent guide to optimizing C++ programs](<a href="http://www.agner.org/optimize/optimizing_cpp.pdf" rel="nofollow">http:&#x2F;&#x2F;www.agner.org&#x2F;optimize&#x2F;optimizing_cpp.pdf</a>). Not for the faint of heart, certainly, but very worth keeping bookmarked.
flohofwoe大约 11 年前
I think the list goes into too great detail, it feels like half of the points are taken care of by the compiler and may change with the used optimization switches or target CPU. For instance: &quot;use shift instead of mul or div&quot;, I remember that this was an issue in the early 90&#x27;s, but I think every modern compiler should be able to figure this out. Or the general advice to pass by-references instead of by-value, this actually backfired on the early Xbox SDK compilers which had SSE-style vector registers, and where it was better to explicitely pass those by-value, since then the compiler would put them into registers (later compiler version would figure this out by themselves, even if pass-by-ref was used).<p>In general, there&#x27;s no way around inspecting the generated assembly code while trying out different optimizer switches and code tweaks, and running the code through a profiler.