netbeans c/c++ (or gcc) & nasm co-work

1. assemble asm to obj 

run: nasm -felf64 maxofthree.asm will generate maxofthree.o


2. 

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值