036.比较利用移位运算和mul指令计算乘法的效率差距

本文通过编程实验对比了两种不同的整数乘法方法:基于二进制位移的乘法与直接使用MUL指令的乘法,在大量计算中各自的执行时间。实验设定循环次数为4,294,967,295次,分别记录并显示两种方法的运行时间,以直观展示其效率差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

; Comparing Multiplications         (CompareMult.asm)

; This program compares the execution times of two approaches to 
; integer multiplication: Binary shifting versus the MUL instruction.

INCLUDE Irvine32.inc

LOOP_COUNT = 0FFFFFFFFh		;一共计算4,294,967,295次乘法‬

.data
intval DWORD 5
startTime DWORD ?

.code
main PROC

; First approach:
							;使用移位的方式计算乘法
	call	GetMseconds		; get start time
	mov	startTime,eax
	
	mov	eax,intval			; multiply now
	call	mult_by_shifting
	
	call	GetMseconds		; get stop time
	sub	eax,startTime
	call	WriteDec		; display elapsed time
	call	Crlf

; Second approach:
							;使用mul指令来计算乘法
	call	GetMseconds		; get start time
	mov	startTime,eax		; 开始计时
	
	mov	eax,intval
	call	mult_by_MUL

	call	GetMseconds		; get stop time
	sub	eax,startTime		; 计算出计时结束时间与计时开始时间的时间间隔
	call	WriteDec		; display elapsed time 利用十进制格式向控制台显示一个32位无符号整数
	call	Crlf

	exit
main ENDP


;---------------------------------
mult_by_shifting PROC
	;
	; Multiplies EAX by 36 using SHL
	;    LOOP_COUNT times.
	; Receives: EAX
	;---------------------------------

		mov	ecx,LOOP_COUNT
	
	L1:	push	eax			; save original EAX
		mov	ebx,eax
		shl	eax,5			;  x*36=(x<<5)+(x<<2)
		shl	ebx,2
		add	eax,ebx
		pop	eax			    ; restore EAX
		loop	L1
	
		ret
	mult_by_shifting ENDP


;---------------------------------
mult_by_MUL PROC
	;
	; Multiplies EAX by 36 using MUL
	;    LOOP_COUNT times.
	; Receives: EAX
	;---------------------------------

		mov	ecx,LOOP_COUNT
	
	L1:	push	eax			; save original EAX
		mov	ebx,36
		mul	ebx
		pop	eax			; restore EAX
		loop	L1
	
		ret
	mult_by_MUL ENDP

END main
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值