run: nasm -felf64 maxofthree.asm will generate maxofthree.o
run: ar -r libmyasm.a maxofthree.o generate libmyasm.a (if use gcc, not Netbeans, this step is not needed.)
3.
Netbeans:
right-click project->properties->Build->Linker->Libraries->Add Library File(Not "Add Library"), Select File type "Static Library(.a)", add libmyasm.a.
(If use gcc, run: gcc maxofthree.o callmaxofthree.c will generate a.out, run it : ./a.out)
Now , it works!!!
; ----------------------------------------------------------------------------- ; A 64-bit function that returns the maximum value of its three 64-bit integer ; arguments.The function has signature: ; ;int64_t maxofthree(int64_t x, int64_t y, int64_t z) ; ; Note that the parameters have already been passed in rdi, rsi, and rdx. ; We just have to return the value in rax. ; ----------------------------------------------------------------------------- global maxofthree section .text maxofthree: mov rax, rdi ; result (rax) initially holds x cmp rax, rsi ; is x less than y? cmovl rax, rsi ; if so, set result to y cmp rax, rdx ; is max(x,y) less than z? cmovl rax, rdx ; if so, set result to z ret ; the max will be in rax
/* * A small program that illustrates how to call the maxofthree function we wrote in * assembly language. */ #include <stdio.h> #include <inttypes.h> #include <sys/time.h> int64_t maxofthree(int64_t, int64_t, int64_t); int64_t maxofthree_c(int64_t a, int64_t b, int64_t c) { int64_t tmp = (a > b ? a : b); return (tmp > c ? tmp : c); } static int count = 100000000; static int64_t a = -10330000000, b = 2003000033, c = 100000003330000; void asm_fun() { struct timeval start; struct timeval end; unsigned long timer; int i = 0; gettimeofday(&start,NULL); for( i = 0; i < count; i++) { maxofthree(a, b, c); } gettimeofday(&end,NULL); timer = 1000000 * (end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec; printf("comparing %d times (assembly) costs %ld us\n", count, timer); } void c_fun() { struct timeval start; struct timeval end; unsigned long timer; int i = 0; gettimeofday(&start,NULL); for(i = 0; i < count; i++) { maxofthree_c(a + i, b - i, c + i); } gettimeofday(&end,NULL); timer = 1000000 * (end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec; printf("comparing %d times (c) costs %ld us\n", count, timer); } int main() { asm_fun(); c_fun(); asm_fun(); c_fun(); return 0; }