计时器汇编程序设计
秒表程序使用了一个 TimeStart 来启动秒表,还有一个 TimeStop 返回自 TimeStart 启动以来
的毫秒数。
程序本身其实很简单,以下为代码:
TITLE Calculate Elapsed Time
; Demonstrate a simple
stopwatch timer, using
; the Win32 GetTickCount function.
INCLUDE Irvine32.inc
TimerStart PROTO,
pSaveTime : PTR DWORD
TimeStop PROTO,
pSaveTime : PTR DWORD
.data
msg BYTE "milliseconds have elapsed" , 0dh , 0ah , 0
timer1 DWORD ?
.code
main PROC
INVOKE TimerStart ,
; 开始计时
ADDR timer1
; 传入一个指向 DWORD 类型的指针
INVOKE Sleep , 5000
; 暂停 5 秒
INVOKE TimerStop,
; 结束计时
ADDR timer1
; 传入一个指向 DWORD 类型的指针
call WriteDec
; 打印一共花费的毫秒数
mov edx,OFFSET msg
call WriteString
exit
main ENDP
;----------------------------------------------------------------------------
TimerStart PROC uses eax esi,
pSavedTime : PTR DWORD
; starts a stopwatch timer.
; Receives : pointer to a variable that will hold
; the current time.
; Returns : nothing
;----------------------------------------------------------------------------
INVOKE GetTickCount
; 得到了时间值,保存在 eax 中
mov esi,pSavedTime
; 得到传入的参数地址
; 将得到的时间值保存在传入的 DWORD 类
mov [esi],eax
型指针所指向的地址中
ret
TimerStart ENDP
;----------------------------------------------------------------------------
TimerStop PROC uses esi,
pSavedTime : PTR DWORD
; 接收一个指向 DWORD 类型的指针作
为参数
; Stops the current stopwatch timer.
; Receives : pointer to a variable holding the saved time
; Returns : EAX = number of elapsed milliseconds
; Remarks : Accurate to about 10ms
; 系统的精确度在 XP 是 10ms
;----------------------------------------------------------------------------
INVOKE GetTickCount
; 又得到了时间,将得到的时间值保存到了 eax
中
mov esi,pSavedTime
; 将接收到指针赋值到 esi 中
sub eax,[esi]
得到自 TimerStart 以来的时间差
; 使用 eax 的值减去目前[esi]中的值记
ret
TimerStop ENDP
END main
注意在 main 之前,有 TimerStart 和 TimerStop 两个函数原型的定义,汇编语言和其他语言
不同,必须在使用之前定义,这样 main 中使用到这两个函数时才会知道,否则程序会认为
找不到这两个函数。