r/Assembly_language • u/sourav_bz • Oct 23 '26
Question At what point writing direct assembly program is more efficient than C program?
Hey folks, this is question coming from the recent podcast where the founders of VLC spoke about, writing assembly level code and it was way more (10x to 62x times) efficient than the C compiled code.
Is there any real example or repo of this which shows the efficiency difference at a smaller scale?
what scenarios do one decide to go full assembly over C, what's the infliction point?
How does anyone even measure these efficiency factors? Is it the instructions executed per clock cycle to attain an end output?
106
Upvotes
54
u/Red_Syns Oct 23 '26
It’s almost impossible to beat a good compiler by writing your own assembly. There are all kinds of wacky operations and tricks a compiler uses to optimize assembly that, as a human, looks nearly incomprehensible.
If you’re one of the dudes with the level of genius it takes to find those operations… maybe? You’d probably be better off writing it in C, compiling, and then looking at the assembly to try and make optimizations, but according to one of my professors beating a modern compiler is a matter of luck and silicon architecture that happens to favor your decisions on that particular machine.
6
u/Diligent_Fondant6761 Oct 23 '26
C is compiled to assembly which then gets converted to machine code and runs....C is just a higher level abstraction over assembly. There are things which C as a programming language does not have...like configuring the CPU etc....those things are still done in assembly but this does not make C slower than assembly...infact C allows you to write assembly directly inside your c files
C is not slower than assembly but there can be usecases where you do not need things which come with c like the standard library ( imagine it as a lightweight runtime) and for those special use case you can write assembly directly!!
2
u/PhilNEvo Oct 23 '26
You likely won't see examples of this at smaller scale, because that's not where you can do this. C's compiler is extremely well-made for general usage, and it's hard to optimize it particularly much.
The situations where writing your own assembly code starts to matter, is in highly specialized areas. A Professor I spoke with, who works with HPC, has to tune his programs with handmade assembly, because he's not writing code for the average PC, but for specialized niche "super computer" stuff.
2
u/Kitchen_Error2578 Oct 28 '26
Your question is very interesting and touches on a key point. The short answer is that assembly language is more efficient than C almost exclusively in very specific hotspots and highly controlled hardware contexts, not in the entire program. The 10x to 62x figure you mention is real, but it has a crucial context: in VLC (and generally in video codecs like x264/FFmpeg), those code snippets are executed millions of times per second and are highly optimized for SIMD instructions (AVX-512, etc.). The C compiler, by design, generates "safe" and generic code; it cannot assume that an array will always have a certain size or that data is aligned in memory in a specific way. The assembly programmer can exploit those assumptions, achieving that speedup.
23
u/Individual-Till-8590 Oct 23 '26
Sometimes, we use inline assembly in C to prevent the compiler from optimizing away certain instructions, ensuring that specific operations are executed as intended. I also noticed assembly instructions in the startup code.
12
u/Illustrion Oct 23 '26
Usually it's not a good idea, but sometimes it's necessary to provide a specific sequence of instructions that must not be interfered with by the compiler.
Consider the code that executed before the CPU cache is enabled. There is no stack yet, the preconditions for running C code haven't been established.
Another example is when you're modifying low level hardware configuration according to a vendor-specified sequence of operation.
6
u/WittyStick Oct 23 '26
Most of the time, an optimizing C compiler will produce assembly as good or better than hand written. Manual assembly is sometimes better for optimizing specific algorithms, for example using AVX-512 with masking - as compilers can miss opportunities to make big performance gains.
You are best writing the bulk of your programs in C and using inline assembly for optimizing specific functions which need it. In some cases you might need to separately link the assembly (eg, MSVC, which doesn't support inline 64-bit assembly).
6
u/Udalrich Oct 24 '26
In several decades of programming, I've written about ten lines of assembly. There was one point in a signal handler where I needed to clear a flag, and the C interface didn't let me do that. So I wrote some assembly to clear the flag and then call the C routine that did the actual work
4
u/Antonio-MTS Oct 23 '26
With assembly you get fast speed and very small size that you cannot usually achieve using compilers of any language like C, C++, Pascal ...
Now the above efficiency usually comes with complexity to port the code to other CPU architectures, maintain, debug it and avoid errors as long as it grows. One incorrect memory addressing in the code may terminate the whole program.
4
u/H9419 Oct 23 '26
The only time it made sense to me is when someone discuss crazy x86 AVX extensions or the equivalent in arm. RPCS3 has plenty of examples but that's still nudging the C compiler to generate the desired assembly
Or if you write DSP assembly which has no equivalent in C
4
u/r3d51v3 Oct 23 '26
The main times I’ve had to actually ensure certain assembly was emitted was during high speed operations that required AVX instructions or other special instruction sets. The compiler wasn’t doing things the way I wanted, despite using the right flags etc. Sometimes it just doesn’t understand what you’re going for. The last time I used it was when I couldn’t get the compiler to understand that the memory I was using was aligned and that I needed to copy from a piece of hardware to happen extremely quickly. I also knew exactly how many 512bit blocks were coming off ahead of time. Additionally I was aware that putting a fence on the operation was actually faster in this case on this architecture, which the compiler wasn’t.
Even then, I could have written this code in assembly, I just used intrinsics because that’s a lot more convenient.
4
u/SuitableAbundance604 Oct 23 '26
I am writing lots of DSP (image/video like VLC is part of it). Often we have high computation loops with relatively short code. So it’s less assembly to write the replacement in the first place. Then, the parallelism and special hardware support for it is something typical compilers would need special intrinsics for. Special DSP compilers can sometimes do this without, but it’s so specific that indeed hand coded assembly can be significantly faster.
3
u/Dazzling_Yak6424 Oct 23 '26
Compiler's just a pre set pass of heuristics containing a mountains load of academic and trial tested knowledge written by academics and CPU manufacturers. It'll make some shameless optimizations that you'd never dare to do like unrolling a loop a million times manually because it found it to be 0.1x faster. But it's also a computer program written so far mostly by humans and may not have necessary logical abstractions to help you make an optimization that you're thinking of or might not have a way for you to supply the necessary information to execute a certain optimization you had on your mind. In that case, you should probably see what assembly did the compiler spit out of your C code and possibly look at the compiler's source code too. And then possibly make some changes with inline assembly. Don't look at it like something you have to rival by writing a perfectly executed and handcrafted neat algorithmic solution that the compiler would otherwise somehow taint with its brutish heuristic passes. In 9/10 cases such a solution doesn't exist and what we currently have encoded is the most optimal solution publicly know to this local problem you're encountering. The universe doesn't like and have neat solutions for most problems, the underlying processor architecture just reflects that. Even your smartest AI, if you put it to such a tiring and nonsensical task, would eventually just create a proto-compiler for itself, crudely rediscovering what others have been piling on and polishing for ages.
1
u/gm310509 Oct 23 '26
IMHO, the answer is never, if not never then extremely rarely.
It also depends upon how you define efficient. If you are talking about project delivery then probably never as assembly takes longer to write than 3GL and higher.
If you are talking about performance efficiency, then same answer, it is often cheaper to set the minimum system specs slightly higher (CPU specs, memory usage) to deliver the required performance that try to squeeze a few clock cycles out of optimised 3GL or higher code. Also, lets say you did squeeze sufficient clock cycles out of the code to squeeze into the current minimum hardware spec, what will happen when you try to deliver V2 and have to keep doing this? The headaches (and cost) simply aren't worth it - IMHO
Now, if you were asking back in the 1960's you would probably have a different calculation.
Also, with all of the above said, there are some scenarios in embedded systems where assembly language is used. A specific example that I am thinking of is where addressable LEDs are used and the manufacturers want to support popular smaller, slower 8 bit MCUs (e.g. AVR). The data rate on these things is sufficiently high that the manufactures often supply drivers that disable interrupts and have extremely tightly controlled code to deliver the data rate needed for it to work properly. Why? Because they can't afford the risk of opimisations being turned on/off that may affect the performance of the code and thus corrupt the data being sent due to bad timing of the (serial) data stream.
But, you asked about efficiency, I wouldn't necessarily classify that as efficiency, more of a necessity. In a project development environment, I would consider efficiency to be "function points completed per day" and assembly language isn't normally my go to solution to meet that metric.
2
u/karchnu Oct 23 '26
Get some documentation about what kind of instructions CPUs have. There are a few operations that can be massively sped up, enabling for example real-time video decoding on modest hardware.
2
u/According_World_7713 Oct 23 '26
IMHO, it depends on target architecture. There are still some architectures around, that are not so good target for C compiler. PIC comes to my mind as primary example. Second case would be special data structures, which are hard to express in C. That is probably the case of VLC.
For me, the infliction point would be that I have full implementation in C, it is kinda lazy and I know exactly why and that I can improve performance by rewritting part of it in assembly.
2
u/ReddyKiloWit Oct 23 '26
Just a comment about deciding too early to go assembly. Guy at a place I worked talked management into buying several Intel assembler packages because he assured them it was the only way to make a particular project fast enough to be usable (in a game engine). I looked at the C code, removed three pointless calls to a square root function, and the assembler boxes were never even opened as far as I know.
The guy never said, but I'm pretty sure the guy was planning on optimizing the square root function without ever wondering if it was needed at all.
2
u/titojff Oct 23 '26
Parts of ffmpeg are assembly
2
u/theNbomr Oct 23 '26
I'm not sure efficiency is always the objective. There can be things a C compiler just can't do, like touching registers that affect the overall state of the CPU (jumping between x86 real mode and protected mode, for instance). Some CPU architectures have address spaces that require special instructions not emitted by the compiler, such some of the bit addresses available in the 8051 family CPUs. There are some compilers that accommodate these kinds of facilities, but they need to be done with extensions that are outside the C standard(s).
2
u/thecratedigger_25 Oct 23 '26
Bootloaders for operating systems. And specific inline asm that shouldn't be optimized away via C compiler. As well as making certain instructions where asm volatile can't reach it.
Other than that, the C compiler does a lot of heavy lifting. There are smaller C compilers out there like musl gcc and tinyC which leaves a smaller footprint than gcc.
2
u/dettus_Xx_ Oct 23 '26
When you want to have full control over your resources.
You can write assembler code without touching RAM, for example.
1
u/gizmo98 Oct 23 '26
If you use SIMD units asm could be better because of parallel operation on multiple bytes/variables at the same time which cannot be expressed in C. Arm neon for example looks more like fpga verilog/vhdl register load/store and compute multiple values at once.
1
u/ElevatorGuy85 Oct 23 '26
Steve Gibson, who runs Gibson Research Corporation (GRC.com), wrote a Windows utility called Wizmo (a portmanteau of “Windows Gizmo”). It’s all of 49KB, and that includes its simplistic GUI and built-in help text.
https://www.grc.com/wizmo/wizmo.htm
Go ahead and try to write even a basic Windows GUI program in C, and you’ll be hard pressed to make it that small, even just a “Hello World” is going to be larger (and it doesn’t nothing truly “useful”).
He’s also written other “pure ASM” tools that are available on the site, e.g. the SpinRite disk tool, that are much larger.
So I would say that pure assembly programs (or portions thereof) can meet several important criteria.
These are my $0.02 cents worth of commentary. I hope that’s helpful!
1
u/tobdomo Oct 23 '26
As long as the problem is small and not too complex, you probably can write more efficient asm than is generated from a decent C compiler (note the word "decent" here!). However, as soon as the complexity is more than just a couple of lines of C code, the compiler should be able to do a better job than many assembly programmers. Lifetime- and register tracking is an area where machines excel compared to humans. Further more, optimization steps after generating (peephole for example) are something that many assembly programmers struggle with; these often require finetuning that falls over as soon as any of the functional code changes.
The middle solution is to have a C compiler generate somewhat optimized code and optimize the generated assembly further by hand. The "12 to 62 times more efficient" claim however is so loosely defined it doesn't make any sense. A "hello world" in small memory model (a.k.a. ".com" on old windows) that doesn't need a library but "pokes" directly in memory, sure. No calling conventions to be taken into account, heavy lifting done in the OS, directly tied to a single hardware environment, sure. As soon as it has to adhere to an ABI for example, no way.
1
u/Joonicks Oct 23 '26
I have a project exploring the speed differences between Asm and C (x86)
biggest factor by far is the algorithm, knowing your hardware, knowing your compiler
but also, in most cases assembly does improve things a little, but you have to be really skilled in your platform to outperform a good compiler
(project: https://github.com/joonicks/ptr64tohex)
1
u/Online_Matter Oct 23 '26
I worked for Unity a few years ago. Huge C++ codebase. The only places using assembly was low-level library functions utilizing the specific instruction sets on various platforms such as the switch and Playstation.
1
u/keelanstuart Oct 23 '26
There are a lot of "media" instructions that have been introduced over the years that would be difficult to generalize by a compiler... because the compiler doesn't have the context you do. These are mostly (all?) SIMD things. I always wondered how a compiler would use the x286 BSF/BSR instructions, even though they might be quite useful.
But in general, if you don't know the instruction set and your domain very well, then it's probably better just to write C.
1
u/21Ali-ANinja69 Oct 23 '26
SIMD, things like AVX
1
u/ziggurat29 Oct 23 '26
Rarely these days. but the C compiler's optimizations are a group of heuristics, and those will not cover every situation, e.g. if it is unaware your processor has some fancy vector math capabilities, you might have to drop to assembly to exploit those.
I think the last time I got a really big boost from assembly was in the mid 90's. The compiler was apparently unaware of the costs of loading a segment register in protected mode and blithely did so with great frequency in an digital filter algorithm when fetching samples from a buffer and putting them in another. Tweaking that to load two segment registers once before processing the buffers sped it up by a factor of 90x. (this was on a 386; the 486 did selector caching and obviated most of that improvement). I'm not saying that there couldn't have been cases for improvement after that, but usually you let poor performance guide you to where to optimize, rather than optimize speculatively.
Other cases routinely done in assembly are setting up registers for OS boot up. that's not really 'efficiency', though, just necessity, and the C compiler is a general purpose tool.
1
u/FitMatch7966 Oct 23 '26
I’d say well into the 1980s
1
u/Nervous-Potato-1464 Oct 23 '26
There are some cases like this https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/21538/files
1
u/Gabriel_AMD Oct 23 '26
Eso depende al algoritmo, si ambos programadores usan el mismo algoritmo, la diferencia es notable, pero se llevará mucho tiempo hacer el programa. La moda actual es dejar un código ineficiente que se ejecute en hardware rápido, para ahorarle trabajo al programador.
1
u/HalifaxRoad Oct 23 '26
I normally just call assembly functions from my C program when I need to manipulate the flash memory, such as things like a bootloader. Other times if I need to do something suuuuper timing critical.
1
u/Reasonable_Return151 Oct 23 '26
No pressure but check out Zazm it is x86-64. I wrote it to get a better understanding of the ISA but it’s turned into way more than that.
Also C optimizes for speed… but in asm you can optimize for size. Good luck getting a 150 byte elf file using C. In the modern age people have lost the art of “tight” clean code.
1
u/IDatedSuccubi Oct 23 '26
Conditional execution and complex loops can be faster in assembly because often times the compiler doesn't fully understand the intent of the code paths
I had this in my software renderer, where there's a few things done per pixel (read: millions of times per second) and some things needed to be conditional and looping but the assembly emitted was creating unnecessary and/or unpredictable branches and using jumps instead of conditional operations etc
Had to fix it by hand, gave like an easy 20-30% boost to FPS IIRC
1
u/PsychologicalBadger Oct 23 '26
In a typical C program your not writing a lot of the code but instead are calling routines that are in a library. These programs can be sluggish or buggy and one reason that languages like C / C++ has its detractors. One of the earliest high level languages Fortran had as its main goal that the compiled code not be significantly slower then assembly. I think this was one of the few high level languages that had that as its primary goal. Anyway be sure your examples between whatever two languages you intend to use are not obscured by huge blocks of library code it just makes the issue that much more difficult to resolve.
1
u/dariusbiggs Oct 23 '26
Performance optimizations when you think you can do better than the compiler with its 5+ decades of work on optimizations.
Compilers, in general, optimize for generic code, things you find in all kinds of programs. So you could get an edge case where hand written for your specific use case can be better.
And of course when you need to do something low level that has no direct correlation to the language and libraries you are using.
These are rare, very rare, most of the time the compiler is the way to go.
1
u/pixel293 Oct 23 '26
It's not the whole program but if you check the "c" directory blake3 code (https://github.com/BLAKE3-team/BLAKE3/tree/master/c) you will find .S and .asm files which contain assembly for the algorithm. The files mostly contain simd instructions. Apparently that was how they got the most speed out of it. However be aware they also have the "reference implementation" done in both C and Rust which are slightly slower, but more readable to most of us.
1
u/keithgabryelski Oct 23 '26
old beard here — i remember when people thought the overhead of c compiler was too much
when c++ was too much
when python ruby and php were too much
when AI was too much
it’s really about balance and for most cases
over 50 years of programming
just don’t care about the specifics and let the thing that lets you describe what you want to do — win
there are cases when performance wins — but again — not common cases
1
u/Distdistdist Oct 24 '26
When you are writing code for low performance embedded systems where cycles might actually matter.
1
u/CamelPure1293 Oct 24 '26
Compilers (at least Microsoft) are still not great in auto-vectorization. Vector code helps for signal processing (audio, images, video), matrix/vector math (including neural networks). Writing assembly is inefficient. What I do at work is using SSE compiler intrinsics in C-like C++ code, telling the compiler which CPU instructions to use. The compiler takes care of register assignment, stack management, instruction ordering etc.
1
u/saf_e Oct 24 '26
When you know what you are doing. Memcpy is a good example.
1
u/kndb Oct 24 '26
The VLC folks were probably talking about coding some form of a software encoder using SIMD instructions directly in Assembly. That would be my only guess. Otherwise most modern compilers are quite good at optimizing your code.
Plus, most bottlenecks happen not because of wrong assembly instructions but because of a wrong code flow, eg allocating memory on the heap too many times, asking for re-allocations and thus moving memory, hitting CPU cache misses way too often, or invoking page faults, using too much virtual memory or making too many trips to the kernel, etc.
1
u/bdblr Oct 24 '26
Biginteger math is much more efficient when written in assembly. I speak from experience when working on an open source crypto library decades ago.
1
u/realestLink Oct 25 '26
I use it for osdev (dealing with hardware, etc.) + some SIMD stuff (tho I technically use intrinsics, not actual assembly technically)
1
u/Illustrious_Trash117 Oct 25 '26
It depends on the compiler the C Code and the processor. RISC Prozessors for example are designed in a way that compilers can generate assembly very efficiently for them. So its hard to beat the C compiler on an ARM CPU.
CISC on the other hand can be hand optimized but its also very hard to beat a good C compiler here.
There is no specific point at which assembly is more efficient than good c code, but generally speaking the more vector extensions of the cpu your programm can utilize the more benefit you can get from writing directly in assembly but it hardly depends on the compiler and if the compiler "understands" your intentions in the C code.
1
u/HKei Oct 29 '26
Usually, you don't write a full program in Assembly. Unless your program is very small, there's no compiler available for your target platform, or you're trying to prove a point. You're writing assembly generally for subroutines where code generated by your C compiler isn't optimal and it matters, because the C compiler is using some patterns and heuristics that work pretty well most of the time, but aren't necessarily optimal for every use case – additionally, you may just be able to produce more efficient code by baking in assumptions about your data that the C compiler isn't allowed to make.
1
u/knobbyknee 29d ago
When writing for a 256 words of memory machine (18 bit words), and you want it to perform multiple tasks, assembly is your only option. There is no compiler that will lay out code to handle the task switching. They will all want to put all the registers on a non existing stack.
1
u/rheladmin 29d ago
For the vast majority of users, writing ASM code will never be more efficient than compiled code.
ASM is mostly an academic exercise these days.
1
u/Quiet-Arm-641 23d ago
I recently wrote a floating point package in assembly that is 76% smaller than the c library code and 1.6-4x faster, depending on what you are doing. Since the target is a microcontroller with 16k flash and 2k ram, this matters.
1
u/Relative_Dare8475 22d ago
Only those architecture dependents, and very critical part like context switch, atomic lock, etc.
0
u/Ok_Tap7102 Oct 23 '26
Almost never. But realistically: when you're left with no other choice, you'll know.
You also have to recognise how ridiculously broad your question is. What are we solving?
A regular GUI running on modern hardware? Hand rolling anything is guaranteed to be complete waste of time to you and whoever the poor bastard has to come debug it the next time (probably also you)
A real-time digital signal processor on an 8 bit microcontroller? Even then vendors provide their own DSP intrinsics (C callable ASM subroutines) for algebraic approximations and FFT primitives... But EVEN THEN if your processing budget is exceeded by microseconds, hand optimising has its place
Exploit development/shell coding during offensive security operations? ALMOST categorically solved for most common usecases with metasploit framework and python pwntools, BUT novel vulns and less mainstream instruction sets will still need some hand crafting
0
u/Pale_Height_1251 Oct 23 '26
Almost never. There is no magic in assembly languages. Any machine code that an assembler can output, a compiler can too
Back in the 1980s, 1990s, sure, before compiler optimisation was as good as it is now, but these days it's highly unlikely you beat a compiler except with contrived demos.
-1
u/vegansgetsick Oct 23 '26 edited Oct 27 '26
performance is achieved by writing good algos, not good assembly
0
u/[deleted] Oct 23 '26
[deleted] — view deleted comment