I wanted to calculate the angle between two vectors but I have seen these inverse trig operations such as acos and atan uses lots of cpu cycles. Is there a way where I can get this calculation done without using these fun开发者_如何转开发ctions? Also, does these really hit you when you in your optimization?
There are no such functions in the STL; those are in the math library.
Also, are you sure it's important to be efficient here? Have you profiled to see if there's function calls like this in the hot spots? Do you know that the performance is bad when using these functions? You should always answer these questions before diving into such microoptimizations.
In order to give advice, what are you going to do with it? How accurate does it have to be?
If you need the actual angle to a high precision, you probably can't do better. If you need it for some comparison, you can use absolute values and the dot product to get the cosine of the angle. If you don't need precision, you can do that and use an acos lookup table. If you're using it as input for another calculation, you might be able to use a little geometry or maybe a trig identity to avoid having to find an arccosine or arctangent.
In any case, once you've done what optimization you're going to do, do before and after timing runs to see if you've made any significant difference.
This is totally implementation defined. Of course, you could use a third-paty implementation, or an approximation, but first you should profile and determine what your bottlenecks are.
If these functions are indeed the bottleneck, and you only need an approximation, you can try using the few first terms of the Taylor series expansion of those functions. The magnitude of the next unused term represents the error in your approximation.
Arccos Taylor series
Arctan Taylor series
The implementations of atan and acos depend on the compiler and the optimization settings. Many implementations will use a table and interpolate to get the nearest value.
Try these things first:
- Profile the application to find the where most of the execution time is spent.
- Redesign this area for better performance.
- Consider Data Driven Design techniques to speed up your program.
- Change logic to reduce branches and if statements, consider using Karnaugh maps to simplify the logic.
精彩评论