Reputation: 21
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.
Upvotes: 2
Views: 248
Reputation: 56956
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.
Upvotes: 2
Reputation: 35059
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.
Upvotes: 0
Reputation: 76539
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.
Upvotes: 1