New in MailingList & Qsocket

Jeff Weeks jweeks at mailandnews.com
Fri Jun 28 21:29:17 BST 2002


> Hi Jeff !
> You just made me curious -
> at first sight I would agree with You (maybe because Your code looks more
> elegant), but I just wrote a small app testing the efficiency of both
> methods. It cycles through a loop 100 million times just to meet the true
> condition for the five different cases of the state.
>
> Here are the results:

[ snip ]

Yeah, that's impressive!  I wasn't expecting that either!

Here's what I got:
carbon:~/tmp$ gcc loops.c -o loops
carbon:~/tmp$ ./loops
state= 0: switch: 610000 ticks (0.61 sec.) --- while: 1150000 ticks (1.15sec.)
state= 1: switch: 600000 ticks (0.60 sec.) --- while: 2010000 ticks (2.01sec.)
state= 2: switch: 620000 ticks (0.62 sec.) --- while: 2930000 ticks (2.93sec.)
state= 3: switch: 610000 ticks (0.61 sec.) --- while: 3820000 ticks (3.82sec.)
state= 4: switch: 600000 ticks (0.60 sec.) --- while: 4680000 ticks (4.68sec.)

However, I optomized the inner loop of the while (just for kicks) to this:
    stateCompare =  -1;
    while(stateInfo[++stateCompare].stateNum != state);

And enabled GCCs optimization, to get this:

carbon:~/tmp$ gcc -O3 loops.c -o loops
carbon:~/tmp$ ./loops
state= 0: switch: 140000 ticks (0.14 sec.) --- while: 190000 ticks (0.19 sec.)
state= 1: switch: 100000 ticks (0.10 sec.) --- while: 340000 ticks (0.34 sec.)
state= 2: switch: 120000 ticks (0.12 sec.) --- while: 340000 ticks (0.34 sec.)
state= 3: switch: 100000 ticks (0.10 sec.) --- while: 660000 ticks (0.66 sec.)
state= 4: switch: 150000 ticks (0.15 sec.) --- while: 860000 ticks (0.86 sec.)

So then I got to thinking how else I could optomize the loop, and it suddenly 
hit me... (and this is a severe oversite on my part!)

If the states are sequential, all you need is an array of strings, and your 
state number is an index into it!!!  I can't believe I didn't think that 
right out of the box!

ie:

char *stateTexts[5] = { "One", "Two", "Three", "Four", "Five" };
stateStr = stateText[QWidget.state()];

I'm pretty sure that's the fastest you're gonna get :)  No loop at all.

Anyway, cheers man, I love optimization riddles like that :)
Jeff

PS: are the states sequential?  Will the above code even work?

-
to unsubscribe from this list send an email to kdevelop-request at kdevelop.org with the following body:
unsubscribe »your-email-address«



More information about the KDevelop mailing list