Solved

# writing fast loop?

Posted on 2004-11-08
245 Views
Dear all,

There are many ways to write a for loop:
for(i=0;i<maxValue<i++){
....
}
Eg)

mov ecx, maxValue
_StartOfLoop:

....
loop: _StartOfLoop

----------------------------
xor eax,eax
_StartOfLoop:

...

cmp eax, maxValue
jnl _StartOfLoop

----------------------------
mov ecx, maxValue
_StartOfLoop:

....
djnz: _StartOfLoop

----------------------------

My Questions are:
1) Is there any other ways that I have missed out?
2)which is the fastest and why? (assume that the value of the counter i would be used in calculation)

thank you.

0
Question by:hengck23

LVL 22

Expert Comment

If you count down to zero you don't need a cmp instruction.

The loop instruction is slower than an explicit "dec ecx; jnz" pair on quite a few CPU's.

You can minimize the loop overhead by repeating the code inside the loop a few times and adjusting the loop count.

0

LVL 9

Accepted Solution

Assume maxValue is an immediate value, and assume this code run on 486
mov ecx, maxValue                  ; 1 clocks
_StartOfLoop:
....
loop: _StartOfLoop                   ; 6 Clocks
so this mathod is 7 clocks

xor eax,eax                             ; 1 clock
_StartOfLoop:
...
cmp eax, maxValue                 ; 1 clock
jnl _StartOfLoop                      ; 3 clocks
this method is 6 clocks

mov ecx, maxValue                  ; 1 clock
_StartOfLoop:
....
dec ecx                                   ; 1 clock
djnz: _StartOfLoop                  ; 3 clocks
this method is 5 clocks
0

LVL 84

Expert Comment

>  You can minimize the loop overhead by repeating the code inside the loop a few times and adjusting the loop count.
Up to the size of your instruction cache
0

## Featured Post

### Suggested Solutions

Patching and EXE 3 1,005
z390 Mainframe Assembly Code Programming 21 885
BufBomb Firecracker 4 2,037
query on MOV assembly instruction 6 556
If you're not part of the solution, you're part of the problem.   Tips on how to secure IoT devices, even the dumbest ones, so they can't be used as part of a DDoS botnet.  Use PRTG Network Monitor as one of the building blocks, to detect unusualâ€¦
DECT technology has become a popular standard for wireless voice communication. DECT devices are not likely to be affected by other electronic devices and signals because they operate in a separate frequency-band.
This video discusses moving either the default database or any database to a new volume.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.