Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a simple example of replacing c code with assembly to improve performance?

Tags:

performance

c

I've heard that game developers will sometimes replace parts of inner loops w/ assembly code to improve the performance.

What is a simple example of this?

Where does the assembly go? Just inline w/ the c code?

Thanks!

Edit: a code sample is greatly appreciated.

like image 388
MrDatabase Avatar asked Nov 30 '22 19:11

MrDatabase


2 Answers

I'm not a game developer, but I write almost nothing but assembly code for a living (I'm a library writer). Generally this is for performance reasons, but I also do it to work around compiler bugs, or to use hardware features like condition flags that are actually easier to express in assembly than in C.

I'm usually writing complete functions in assembly, so I tend to write .s files that are assembled into object files and linked into an executable or library. People who just need to move a single loop into assembly often use inline assembly in their C source, which is supported by most compilers via some sort of intrinsic.

"Simple" examples are pretty rare, since if it was simple, the compiler would do a sufficiently good job and there would be no need for assembly.

like image 82
Stephen Canon Avatar answered Dec 16 '22 01:12

Stephen Canon


Here are the assembly coding pros:

  • Assembly code can take advantage of a processor's unique instructions as well as various specialised hardware resources. On the other hand, C code is generic, and must support various hardware platforms. Thus, it is difficult for C to support platform-specific code.

  • The assembly programmer is usually very familiar with the application and can make assumptions that are unavailable to the compiler.

  • The assembly programmer can use human creativity; the compiler, advanced as it may be, is merely an automatic program.

On the other hand, here are the assembly coding cons:

  • The assembly programmer has to handle time-consuming machine-level issues such as register allocation and instruction scheduling. With C code, these issues are taken care of by the compiler.

  • Assembly coding requires specialised knowledge of the DSP architecture and its instruction set, whereas C coding only requires knowledge of the C language—which is rather common.

  • With assembly code, it is extremely difficult and time consuming to port applications from one platform to another. Porting is relatively easy for C applications.

from here

like image 33
Sorantis Avatar answered Dec 16 '22 02:12

Sorantis