Re: Subtract smaller or larger number from x?
- From: Gerry Quinn <gerryq@xxxxxxxxxxxxxxxxxxx>
- Date: Thu, 30 Mar 2006 11:10:15 +0100
In article <20060329145340.f93b3f3b.steveo@xxxxxxxxxx>,
steveo@xxxxxxxxxx says...
So in addition to doing the subtraction and a test it is doing a
function call and perhaps a negation - whereas the original is doing a test
and a subtraction. Seems pretty certain to be less efficient to me.
This version might be more efficient but I doubt it, it probably
compiles to pretty much the same code as the original. It is perhaps a
little prettier.
diff = (y > x) ? y - x : x - y;
On an old fashioned CPU, the following might be closest to the most
efficient assembly:
int val = y - x;
if ( val < 0 )
{
val = -val;
}
The reason being that a comparison is effectively a subtraction that
sets the relevant flags but leaves the data unchanged. So you might as
well do the subtraction immediately to get the sign flag. It would
look something like:
move A, y
sub A, x
jump on not negative END
add A, x ; if no 2-s complement operator available
add A, x
END:
But if conditional jumps are expensive but the CPU has a built-in abs
operation, that's going to be best.
- Gerry Quinn
.
- Follow-Ups:
- References:
- Subtract smaller or larger number from x?
- From: eksamor
- Re: Subtract smaller or larger number from x?
- From: upeksharuvani
- Re: Subtract smaller or larger number from x?
- From: Steve O'Hara-Smith
- Subtract smaller or larger number from x?
- Prev by Date: Re: String concatenation design
- Next by Date: Re: String concatenation design
- Previous by thread: Re: Subtract smaller or larger number from x?
- Next by thread: Re: Subtract smaller or larger number from x?
- Index(es):
Relevant Pages
|