performance - Extremely slow object instantiation in Python 2.7 -


i had complete assignment used lot of coordinate operations. thinking save time , simplify code, defined class encapsulate behaviour of coordinate pair. class looked this:

class vector (tuple) :     def __init__ (self, value) :         tuple.__init__ (self, value)       def __add__ (self, other) :         return vector ((self [0] + other [0], self [1] + other [1])) 

this allowed me write code (for example):

def translate (pointlist, displacement) :     return [point + displacement point in pointlist] 

but application terribly slow. slower other assignments. couldn't locate inefficiency in implementation of algorithm, did simple test see overhead of vector class. expected somewhere between 5% , 15%.

my test of vector class looked this:

v = vector ((0, 0)) d = vector ((1, -1)) loopidx = 3000000 while loopidx > 0 :     v = v + d     loopidx -= 1 print (v) 

this runs (typically) in kind of time:

real    0m8.440s user    0m8.367s sys     0m0.016s 

for comparison ran code:

v = (0, 0) dx = 1 dy = -1 loopidx = 3000000 while loopidx > 0 :     v = ( v [0] + dx, v [1] + dy )     loopidx -= 1 print (v) 

run time code is:

real    0m1.004s user    0m0.995s sys     0m0.006s 

have done wrong, or using class objects in python mean application take on 8 times long run?

not answer how make class faster, more of alternative.

instead of subclassing tuple , writing add, sub etc. methods yourself, cold use python's bultin complex number type 2d coordinates, has operations built in, correct , and super-fast.

>>> %timeit vector_no_init() 1 loops, best of 3: 1.39 s per loop >>> %timeit plain_tuple() 1 loops, best of 3: 403 ms per loop >>> %timeit complex_nums() 1 loops, best of 3: 171 ms per loop 

for rotation, can use complex multiplication: multiply complex coordinate complex number has, in polar form, absolute value 1 , phase equal angle want rotate by. rotate 90 degrees, can multiply 1j (anti-clockwise) or -1j (clockwise). other angles, use cmath module translation , polar form.

>>> c = complex(4, 2) >>> c * cmath.rect(1, math.radians(45)) (1.4142135623730954+4.242640687119285j) 

however, suggest not subclass complex make rotate method of class, because in case have overwrite other methods, add, well, otherwise result of addition regular complex number, not providing rotate method. , undo performance gains, making slow vector class. instead, make function rotate(complex, angle) -> complex.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -