# [Numpy-discussion] Faster way to generate a rotation matrix?

Lou Pecora lou_boog2000@yahoo....
Wed Mar 4 06:52:54 CST 2009

```First, do a profile.  That will tell you how much time you are spending in each function and where the bottlenecks are.  Easy to do in iPython.

Second, (I am guessing here -- the profile will tell you) that the bottleneck is the "call back" to the rotation matrix function from the optimizer.  That can be expensive if the optimizer is doing it a lot.  I had a similar situation with a numerical integration scheme using SciPy. When I wrote a C version of the integration it ran 10 times faster.  Can you get a C-optimizer?  Then use ctypes or something else to call it all from Python?

-- Lou Pecora,   my views are my own.

--- On Tue, 3/3/09, Jonathan Taylor <jonathan.taylor@utoronto.ca> wrote:

> From: Jonathan Taylor <jonathan.taylor@utoronto.ca>
> Subject: Re: [Numpy-discussion] Faster way to generate a rotation matrix?
> To: "Discussion of Numerical Python" <numpy-discussion@scipy.org>
> Date: Tuesday, March 3, 2009, 11:41 PM
> Thanks,  All these things make sense and I should have known
> to
> calculate the sins and cosines up front.  I managed a few
> more
> "tricks" and knocked off 40% of the computation
> time:
>
> def rotation(theta, R = np.zeros((3,3))):
>     cx,cy,cz = np.cos(theta)
>     sx,sy,sz = np.sin(theta)
>     R.flat = (cx*cz - sx*cy*sz, cx*sz + sx*cy*cz, sx*sy,
>         -sx*cz - cx*cy*sz, -sx*sz + cx*cy*cz,
>         cx*sy, sy*sz, -sy*cz, cy)
>     return R
>
> Pretty evil looking ;) but still wouldn't mind somehow
> getting it faster.
>
> Am I right in thinking that I wouldn't get much of a
> speedup by
> rewriting this in C as most of the time is spent in
> necessary python
> functions?
>
> Thanks again,
> Jon.

```