

Ask HN: Inline assembly. When do I need it? - moccajoghurt

I read the article about the beauty of the Doom 3 source code and stumbled upon the mention of inline assembly parts.
When is the C or C++ compiler not sufficient and you actually need to write assembly code?
It's something I wouldn't have expected.
======
wtracy
I would say: Whenever you have a hard performance target that you must hit,
and pure C can't meet that target.

Every game, including Doom 3, has some targeted minimum frame rate that the
developers want it to run at. (This target can be anywhere from 30-60 frames
per second, depending on the studio's standards.) Additionally, the game will
have some targeted hardware that it is expected to run on. (Hardware
requirements for PCs may slip during development, but console hardware is
pretty non-negotiable.) The developer will optimize until the game runs at the
required frame rate on all the targeted hardware platforms (using a profiler
to identify the functions that need optimization) then no further.

Now, if what you really meant is, "When is assembler actually going to be
faster than pure C?" that's a harder question. Modern C compilers are pretty
smart, and most assembly hackers today start by looking at the assembly
generated by a C compiler, and optimizing from there.

Most compilers are conservative about what optimizations they run, so there
are often situations where it is safe to apply an optimization yet the
compiler will not recognize it as such. (Really, would you want your compiler
adding bugs to your code in an effort to make it "faster"?) So, sometimes you
can apply optimizations that the compiler missed.

Most of the time, though, if you're not John Carmack then you probably can't
beat your C compiler.

------
J_Darnley
Whenever you want to use simd. I have not yet seen a multimedia project say
"The compiler does the right thing here". This may not apply to games and
almost certainly does not to most programs.

------
trin_
you'll know it when you need it ... seriously. unless you really know what you
want and what you are doing the chances of outsmarting the compiler are very
very slim.

there's a rather old but good video about this very topic that i just
remembered:

[http://media.ccc.de/browse/conferences/camp2007/cccamp07-en-...](http://media.ccc.de/browse/conferences/camp2007/cccamp07-en-1952-Know_your_compiler.html)

and i think these are the corresponding slides: <http://www.fefe.de/know-your-
compiler.pdf>

------
mattgrice
When the code isn't fast enough and you know some trick or shortcut that the
compiler doesn't know or can't use.

------
meaty
Probably never these days.

