Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Fascinating! How does one learn to write C code that will make use of specific asm instructions?

SIMDjson is another example that comes to mind. The conceit of C is that you do t have control over the underlying machine instructions without inlining it yourself. So how do people write C code with cpu optimizations like this?



There are three approaches:

1) Use intrinsics, if your platform provides intrinsics for the instructions you want to use.

2) Use inline assembly (which I suppose doesn't technically count as writing C code, but is very much part of the story).

3) Write C code carefully against a chosen compiler with chosen optimization flags, and inspect the assembly. Especially for small chunks of code, a tool like godbolt.org is indispensable. Basically, you're writing the assembly you want the compiler to generate (either explicitly, or just in your head), then writing C code that seems likely to generate that sequence of instructions, then tweaking the code until the output you want is generated. If this is a super important optimization, it's also reasonable to add a build step that inspects the generated assembly and fails the build if it doesn't match the desired pattern; but in that case, writing inline assembly is usually easier.


Option 4 is sometimes compiler annotations like __builtin_expect_with_probability which you could use to assign a branch a value of 50% which should coerce it to pick cmov (same risk as 3 though in that you need to inspect compiler output).


Yep, there's an entire book to be written on techniques that you can use to express your understanding of code to the compiler so that the compiler's chosen implementation of it matches yours. Plenty of __builtins and __attributes__, and even just the ordering of if/else statements, grouping statements into local scopes with {}, using or not using a temporary variable...


I would say it is a moving target if the goal is to write C code that compiles to a seemingly magical cpu instruction. As other have pointed out, learning assembly and compiler explorer are useful things.

As a way to show the wonderful complexities of compilers check the TOC of https://shop.elsevier.com/books/optimizing-compilers-for-mod...


Use inline assembly or intrinsics. Read the code of stuff that does these things.

Resources sufficient for implementing simdjson or similar vectorized parsers: https://www.intel.com/content/www/us/en/docs/intrinsics-guid... https://lemire.me/blog/ http://0x80.pl/articles/




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: