[Edu-sig] Introducing Python to Engineering Students
David MacQuigg
macquigg at ece.arizona.edu
Wed Mar 12 16:20:25 CET 2008
At 07:24 PM 3/11/2008 -0700, Rob Malouf wrote:
>On Mar 11, 2008, at 5:11 PM, David MacQuigg wrote:
>>It would make a nice improvement in this Mandelbrot demo if you
>>could show me a way to significantly improve the speed of the Python
>>I already have, perhaps avoiding the need for C.
>...
>Or, instead, replacing your getpts with the weave-d version:
>
> from numpy import zeros
> from scipy import weave
> ...
> vals = zeros(100,int)
>
> code = r"""
> double cx = cx0 - dx;
> for (int p=0; p<100; p++) {
> double zx = 0.0;
> double zy = 0.0;
> int i;
> cx += dx;
> for (i=0; i<999; i++) {
> double zx2 = zx*zx;
> double zy2 = zy*zy;
> if ((zx2 + zy2) > 4.0) break;
> zy = 2*zx*zy + cy0;
> zx = zx2 - zy2 + cx;
> }
> vals[p] = i;
> }
> """
> weave.inline(code,['cx0','cy0','dx','vals'])
>
>I get:
>
> 1a) Python speed = 102200 points/sec
> 1b) C speed = 103300 points/sec
> 2a) Python speed = 108400 points/sec
> 2b) C speed = 110700 points/sec
Excellent!!! This is exactly what we need. Our students will have no problem writing the C code string, and the Python wrappings are simple enough they can just follow this example verbatim.
>There's probably a more pythonic way to write that, but
>this'll do. And after all, this is a realistic situation: you've got
>the inner loop of a program written in C, but you'd rather write all
>the supporting code around it in something like Python. And note that
>weave automatically compiles and links (if necessary) and then loads
>the C part when you run mandel.py. You (or your students) don't need
>to remember where the python headers are or how to build a shared
>library on whatever platform they're using.
That was my next problem. Our students use mostly Windows, some on MacOS, and a few on Linux. If all we need beyond the latest Python is numpy and scipy, that is great!!
I'll have to experiment with this later. Many thanks.
-- Dave
More information about the Edu-sig
mailing list