PocketMatrix forums

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

A Question of Speed :)

here is an interesting question:

if you were testing for 5 things to be true, would it be faster to test the first, then if it passes then next etc (if then else) of all at once (if & and)

e.g
Code:

bool click_area(int x1,int y1,int x2,int y2)
{
if ((clickxpos() > x1) && (clickxpos() < x2) &&
(clickypos() > y1) && (clickypos() < y2) && clicked())
{
return 1;
}
else return 0;
}


or

Code:

bool click_area(int x1,int y1,int x2,int y2)
{
if (clickxpos() > x1)
if (clickxpos() < x2)
if (clickypos() > y1)
if (clickypos() < y2)
if clicked()
{
return 1;
}
else return 0;
}


-any ideas, insights....... (I think the latter, but....) :)
brendan · 17 Apr 2002, 00:06 UTC — OR
Code:

bool click_area(int x1,int y1,int x2,int y2)
{
int xpos = clickxpos();
int ypos = clickypos();
if (xpos > x1)
if (xpos < x2)
if (ypos > y1)
if (ypos < y2)
if (clicked())
{
return 1;
}
else return 0;
}


;)
The first example will not be any slower. In fact, it may be faster, because all the logic is grouped in one place, making it easier for the compiler to optimize it. Logical operators are evaluated from left to right. As soon as a condition fails it will jump to the appropriate code in the if / else statement. That allows something like this to work properly:

if (pMyVar && *pMyVar)
//something

"something" will only be evaluated if the pointer pMyVar is not NULL, and the value it points to is non-zero. The dereferencing (*pMyVar) does not take place if the first condition fails. If it did then an exception would occur.

To expand on that (conditional evaluation), here is an easy mistake to make. Say you have a boolean flag that once set to true stays true. Compare the two versions below.

Code:

bool bFlag;
bFlag = DoSomething()
bFlag = DoSomethingElse() || bFlag;
bFlag = DoAnother() || bFlag;


Code:

bool bFlag;
bFlag = DoSomething()
bFlag = bFlag || DoSomethingElse();
bFlag = bFlag || DoAnother()


Now, the second example is very bad. At first glance
it appears fine. If bFlag is already true, then it will stay true. If it is not already true, then the function's return value will set it. The second version is bad because in lines 3 and 4, if bFlag was already true, then the second condition (the function call) will not be executed.

Make sense?

Dan East
Going along with Dan's order of execution comments, you'll probably want to take move the test for clicked() first, so that you can jump out early. I'd probably also write a single version of those other functions that returned both the x and y position in a single call, or at a minimum declare the two functions as _inline.

Compile your code with the /FAcs switch then look at the resulting .cod file and see what the compiler has generated for your C code. If that's over your head, then profile the code as you muck with it to see which is actually faster.
crickies mate!!! :o

so this is basically as fast as it goes:

Code:

bool click_area(int x1,int y1,int x2,int y2)
{
int xpos = clickxpos();
int ypos = clickypos();
if (clicked() && (xpos > x1) && (xpos < x2) && (ypos > y1) && (ypos < y2)) return 1;
return 0;
}

I don't know what involed in the clickxpos() etc, but I figure storing it once to be used twice would be quicker.....

-Brendan
Right, you are better off storing it in a temporary variable if you're going to use a return value more than a couple times.

To expand on what Digby said, it simply makes sense to determine what conditions are most likely to cause the whole expression to fail. If you want to get very nit-picky, note that you check X first to make sure it is in range. Well, on a Pocket PC there are 33% "more" Y values than X. So assuming we're talking about square regions (on average), you should check Y first, as it has a higher probability of falling outside the range. :)

Dan East
brendan · 17 Apr 2002, 06:00 UTC — OK....ish
ok so the following code should be the fastest...

Code:

bool click_area(int x1,int y1,int x2,int y2)
{
int xpos = clickxpos();
int ypos = clickypos();
if (clicked() && (ypos > y1) && (ypos < y2) && (xpos > x1) && (xpos < x2))
{
return 1;
}
else return 0;
}


only problem is: it don't work, but this does:

Code:

bool click_area(int x1,int y1,int x2,int y2)
{
int xpos = clickxpos();
int ypos = clickypos();
if ((ypos > y1) && (ypos < y2) && (xpos > x1) && (xpos < x2) && clicked())
{
return 1;
}
else return 0;
}


work that one out ? it compiles as one would expect, but the func always return 0.. ? are there issues calling clicked() func to soo after the clickxpos etc ?
As soon as a condition fails it will jump to the appropriate code in the if / else statement.

It's technical name is "short circuiting". You have to be careful with it sometimes, because some languages short-circuit, and some don't. :(

A function that small would probably benefit from being an inline function...

.. and well done for sticking the "else" in there, even though you don't need it. :) My only pedantic C grammar gripe now is that it's lacking the {} s around the else code. :D

My next comment goes with what Dan and Digby said...

At the moment you're checking for the value being IN range... where usually the range OUTside is bigger... so probabalistically speaking, you should probably :wink: do something like:

Code:
if ((ypos>y2)||(ypos<y1)||(xpos>x2)||(xpos<x1))
{
// check for OUT of range first
return 0;
}
else
{
if (clicked())
{
return 1;
}
}
return 0;


... it all depends on your data. The code is a little nastier with the extra exit point.. but that's alright for such a small function IMO.

Incidentally, I suspect that optimising this function is pretty pointless...unless you're using it a lot..? Your recently discussed "tile plotter" would be a much more sensible area to target, IMHO. That's not to say that this discussion hasn't been useful, of course :D

Unless I'm missing some precedence rule, the two pieces of code you posted should be equivalent, IMO.

Cheers,

Refractor
This doesn't directly pertain to the question, but I'm going to throw it out here anyway.

Above I stated that logical expressions are evaluated from left to right. Since we know that explicitly, we can optimize and otherwise achieve the desired behavior. Conversely, there are things in C/C++ that are not defined, thus we cannot "fine tune" our code in the same way. The main area is in the passing of arguments for function calls. The ANSI C specification states that the order in which arguments are evaluated is undefined, and is left up to the compiler. So, here's an example of what not to do:
Code:

void DoSomething(int a, int b, int c) {
}

void CallDoSomething() {
int i=1;
DoSomething(i++, i++, i++);
}


Now then, what exactly was passed to DoSomething as a, b and c? We don't know. Depending on the compiler it would be either a=3, b=2 and c=1 OR a=1, b=2, c=3. Many compilers will pass the values from right to left, while others evaluate arguments from left to right. I suppose it is possible for a compiler to exhibit "random" behavior, by passing arguments by their type, for example.

So the lesson is that C/C++ allows you to compound statements together to a great degree. Many coders take these shortcuts simply because they result in less typing and more compact source code. However, there can be serious drawbacks, such as the one mentioned above, as well is making some things impossible to debug properly.

Dan East
Brendan, what does the clicked function do? Is that an EasyCE routine?

Dan East
Brendan, I think the problem where you get always a 0 as the return value:

Code:

bool click_area(int x1,int y1,int x2,int y2)
{
int xpos = clickxpos();
int ypos = clickypos();
if (clicked() && (ypos > y1) && (ypos < y2) && (xpos > x1) && (xpos < x2))
{
return 1;
}
else return 0;
}


the values of clickxpos() and clickypos() are undefined (well, not really they actually contain the previous click values). They will take the real values once there has been a click on the screen (they are populated with the WM_LBUTTONDOWN message) so that your if statement above checks for xpos and ypos before it actually checks for a click (I think eVC++ evaluates parameters right to left). So effectively you check the coords before you even know whether there has been a click on the screen.

And Dan, the clicked() function is indeed an EasyCE call that returns true if there has been a tap on the screen since the last check.

I'm beginning to think I didn't make much sense right there... sorry but it's the end of a looooong day.

AL
refractor,

Shouldn't you check for clicked() first? It seems like that has a less chance of being true than the click being inside/outside the rect. That's just my wild-assed guess. (not knowing how frequently the posted code is called, or the overhead of those called functions, we're all making blind assumptions)

I'm surprised no one else suggested looking at the code the compiler generates, or actually profiling to determine which is faster. Where did you guys go to school? (j/k) :)
I am surprised to see how much posts are generated for something you usually don't have to optimize at all...

On the other hand, the discussion about the order of evaluation is something worth explaining.
"so that your if statement above checks for xpos and ypos before it actually checks for a click (I think eVC++ evaluates parameters right to left)."-alfonso

so is it left to right or right to left ?

there seems to be a difference in opinions here ?

BTW refractor, good idea....(your func)

-Brendan
Sorry brendan,

Dan is right, the conditional evaluation is actually left to right.

I did warn you, yesterday was a long day indeed! And I still spent 4 hours after work doing some coding on my iPaq ;)

Incidentally, I know I'm going to make myself a reputation for being pedantic, but a small correction is necesary to Dan's comment on parameter passing order. Namely

Code:

void DoSomething(int a, int b, int c) {
}

void CallDoSomething() {
int i=1;
DoSomething(i++, i++, i++);
}


is not a problem, but this is

Code:

void DoSomething(int a, int b, int c) {
}

void CallDoSomething() {
int i=1;
DoSomething(++i, ++i, ++i);
}


Also, you'll find that eVC++ does evaluate parameters right to left (the reverse order that conditional evaluation). So the function DoSomething(int a, int b, int c) above will be initialised with the following values

Code:

a = 4;
b = 3;
c = 2;


Cheers!
AL
Digby:

Yes, you're right, of course :) The clicked should be outside the loop. My mistake. I didn't mention checking the assembly code 'cos you did. :D

Brendan:

The difference in opinion (right-left vs left-right)is because there isn't a definitive way of doing it - it's, unfortunately, compiler specific (certainly for C++ - I just looked in the reference :)).

From the Microsoft help, it says:

Operators in the same group have equal precedence and are evaluated left to right in an expression unless explicitly forced by a pair of parentheses, ( ).


Things like the assignment operations remain right-left of course :)

Cheers,

Refractor
Alfonso, the example I provided is "correct", in that it will fail as I said it would, and is bad coding practice. You example will also fail.

Dan East
Oops!

Sorry about that. The above post is mine, apparently the autologin didn't feel like working this morning ;)

AL
Dan,

the example you provided will get all three parameters initialised as

Code:

a = 1;
b = 1;
c = 1;


as expected, since the post-decrement will wait until you return from the call before acting. So there is no problem as in guessing the values of a, b and c in this case, where there is if you use pre-decrement.

I told you I would make myself a reputation for being pedantic. I apologise, and I'm honoured to be talking to you since I've always thought of you as "the man" when it comes to PocketPC programming :)

Cheers!
AL
Alfonso, you're correct. I was quite sure that post-decrement exhibited that behavior as well, but it does not. We hashed this out at YSU a decade ago, and I had thought I had tested both pre and post decrement.

Dan East
Testing a range can be done with only one comparison

So, rather than

if (x>=x1 && x<x2)

can do this:

if ((unsigned) (x-x1)<(unsigned) (x2-x1))

You can get the <0 range of the number line tested for free with unsigned. Also try and bring the x2-x1 calc upstairs - so you can do this only once, not per test.

Only worry if you're sure you've got a performance hit here though

Cheers