Comparison between countdown program in x86 assembly language, C++ and Python
Created by Phil Gardner
last edited Feb 17 2021 by Phil Gardner
Accompanied by INCREDIBLY INTERESTING observations. Yeah!
What’s this about? Difference between translators (assembler, compiler, interpreter). Difference between low-level code and high-level languages. The mythical “do-while” loop (you may have heard whisperings of this… IT REALLY EXISTS!) Shows you a few real assembly language mnemonics that are used by Intel CPUs: mov (move), dec (decrement value by 1), jg (jump to labelled section if result is greater than zero).
The C++ version uses a do-while loop. It is intended to be as close to the assembly method as I can get it (always room for improvement here…) hence I am not using a for loop. The do-while and the assembly language conditional jump do the same thing: execute a few instructions, then decide afterwards to perform another iteration.
The Python version uses a while loop (no do-while construct in Python) to make it as close to the other two as I could. Equally, I could have used for loops for both the Python and C++ versions.
One technique in optimising assembly language loops is to “unroll” them, manually reproducing the body of the loop again and again. I’m not going to do that here. 1 billion iterations!
The C++ code was compiled using GNU Compiler Collection g++ compiler for Windows 10. Not necessarily the fastest compiler and I used the default options, without looking for ways to optimise the generated code or compilation process. Different compilers may well produce better results.
The assembly source was assembled using the HLA assembler. Again, other assemblers may produce very different results in terms of timings.
Further examples of C++ programs for GCSE and A-level students… C++ here
Examples of assembly language programs… Intel x86 assembly here