PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Integer Square Root (ASM)

Hi.

I've written an integer square root in asm, and I'm a bit rusty when it comes to ARM assembler (it's been a while...)

From the algorithm it's the well known 2 bits per iteration method. I jut use clz to skip all unnessesary iterations for numbers smaller than 32 bits.

Any ideas how to improve it? I thought about unrolling the code and calculate a jump offset based on the leading zero count, but I doubt that this will be much faster due to the code caching (the code would grow up to about half a kilobyte).

Code:

isqrt PROC
CLZ R1, R0
MOV R3, #1
RSB R1, R1, #31
MOV R2, #0
MOV R1, R1 LSR #1
MOV R3, R3 LSL R1
|nextbits|
ADD R12, R3, R2 LSL #1
MOV R12, R12 LSL R1
CMP R0, R12
SUB R1, R1, #1
ADDCS R2, R2, R3
SUBCS R0, R0, R12
MOVS R3, R3 LSR #1
BNE |nextbits|

MOV R0, R2
MOV PC, LR
ENDP


Bye,
Nils
So - PocketMatrix is dead for real developers, right?
Refractor just hasn't swung by in a couple days. :)

Dan East
Sorry for the delay - I have no internet connection at home yet and frankly this place is so dead that I haven't visited for quite some time anyway.

First thing:

http://www.finesse.demon.co.uk/steven/sqrt.html

might give you some other ideas if you've not found it already. I'm afraid I only had enough time to "optimise" the code you posted, and even that is dubious. :( Let me know if it helps (either you and performance) ;)

Optimising the code:

1. Removed "MOV R12, R12 LSL R1" by amalgamating "R12 LSL R1" into both the CMP and SUBCS (and moving the R1 decrement). On a CPU where register controlled shifts hurt this should be the same performance as the original (with slightly smaller code).

2. Moved "MOV R2, #0" between the "MOV R3, R3 LSL R1" and "ADD R12, R3, R2 LSL #1" for CPUs where a register controlled shift adds result latency.

Code:
isqrt PROC
CLZ R1, R0
MOV R3, #1
RSB R1, R1, #31
MOV R1, R1 LSR #1
MOV R3, R3 LSL R1
MOV R2, #0
|nextbits|
ADD R12, R3, R2 LSL #1
CMP R0, R12 LSL R1
ADDCS R2, R2, R3
SUBCS R0, R0, R12 LSL R1
SUB R1, R1, #1
MOVS R3, R3 LSR #1
BNE |nextbits|

MOV R0, R2
MOV PC, LR
ENDP