Skip to content

Instantly share code, notes, and snippets.

@seisvelas
Last active December 10, 2018 20:13
Show Gist options
  • Save seisvelas/a09fb1650a6bffbd7dc8393edf9462f5 to your computer and use it in GitHub Desktop.
Save seisvelas/a09fb1650a6bffbd7dc8393edf9462f5 to your computer and use it in GitHub Desktop.
Learnin' C
#include <stdlib.h>
int main(void) {
int edi = 5; // nth fib num
int ebx = 0;
int eax = 1;
int edx; // tmp
start_loop:
--edi;
if (edi==0) { goto loop_exit; }
edx = eax;
eax += ebx;
ebx = edx;
goto start_loop;
loop_exit:
return ebx;
}
.section .data
.section .text
.globl _start
_start:
movl $10, %edi # number of fibnum we hunt
movl $0, %ebx # 1st fibnum
movl $1, %eax # 2nd fibnum
arb_label:
## Check if %edi is 0
## (thus meaning %ebx is nth fibnum)
## and if so, exit loop
decl %edi
cmpl $0, %edi
je loop_exit
## core Fibonnaci algorithm
## (hold %eax in tmp register %edx,
## eax = eax + ebx,
## ebx = edx)
movl %eax, %edx
addl %ebx, %eax
movl %edx, %ebx
jmp arb_label
## Once loop completes...
loop_exit:
movl $1, %eax
int $0x80
@seisvelas
Copy link
Author

seisvelas commented Nov 30, 2018

@informatimago

My handwritten assembly code written without optimization in mind outperforms GCC's assembly compilation of your code in terms of speed.I am using the Linux time command. How strange. I don't know why.

edit: Well, I have an idea of why (your program makes use of a pricey function call that gives my function-less version a slight edge). But what I mean to say is, I don't know why GCC at -O3 can't optimize away the function call entirely.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment