开发者

Efficient way to project vectors onto unit box

I am reimplementing a Matlab function in C for performance 开发者_开发技巧reasons. Now, I am looking for the most efficient way to compute the projection of a vector onto the unit-box.

In C terms, I want to compute

double i = somevalue;
i = (i >  1.) ?  1. : i;
i = (i < -1.) ? -1. : i;

and since I have to do this operation several millions of times I wonder what could be the most efficient way to achieve this.


If you're on 686, your compiler will likely transform the conditional into a CMOV instruction, which is probably fast enough.

See the question Fastest way to clamp a real (fixed/floating point) value? for experiments. @Spat also suggests the MINSS/MINSD and MAXSS/MAXSD instructions, which can be available as intrinsics for your compiler. They are SSE instructions, and may be your best choice, again, provided you're on 686.


If you/"the compiler" use(s) the IEEE 754 double format, I'd think reading the first bit (the sign bit) of the double's memory is probably the most direct way. Then you'd have no additional round or division operations needed.


Did you consider using SSE instructions to speed up your code?

Also you could use OpenMP to parallelize you code, and thus making it faster.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜