Moi
10/22/2009 10:42:00 PM
On Thu, 22 Oct 2009 15:07:58 -0700, user923005 wrote:
> On Oct 22, 2:24??pm, Moi <r...@invalid.address.org> wrote:
>> int median3(int a,int b,int c)
>> {
>> switch ((a>b)+((b>c)<<1)+((c>a)<<2)) { case 0: return a;
>> case 1: return c;
>> case 2: return a;
>> case 3: return b;
>> case 4: return b;
>> case 5: return a;
>> case 6: return c;
>> ?? ?? ?? ?? }
>>
>> }
>>
>
>
> Surprising to me, the switch ran 4x slower than the simple if() tests.
>
> It appears that the missed branch predictions are killer. I guess that
> profile guided optimization will help your routine quite a bit if the
> data has some particular pattern. */
Thanks for benchmarking. It was not intended to be a racer...
There are probably too many sequence points and too few common
subexpressions to give the compiler enough freedom to optimise.
There are other cases where this "computed enumeration" method can save
you some headaches. (e.g. 2D range-compare) It is relatively easy to
build and test, even if the conditions get very complex. The cases where
you know beforehand that you won't get it right the first time.
AvK