Performance penalty for using classes?

Tim Churches tchur at optushome.com.au
Mon Jan 13 01:33:43 EST 2003


On Sat, 2003-01-11 at 22:04, Miki Tebeka wrote:
> Hello All,
> 
> I need my M.Sc. to run fast but I don't want to recode it in C.
> I've noticed that using classes can cause my code to run about 30%
> slower.
> (See the below tests)
> 
> Since I don't need OO much in this project is it worth moving to a
> non-OO programming style?
> 
> Miki
----snip-----

Why not use Psyco (see psyco.sf.net):

#----class_test.py--------
#!/usr/bin/env python
import random, time

class Dot:
    def __init__(self, x, y):
        self._x = x
        self._y = y

    def x(self):
        return self._x

    def set_x(self, x):
        self._x = x

    def y(self):
        return self._y

    def set_y(self, y):
        self._y = y
    

def test_class(iterations):
    while iterations > 0:
        d = Dot(random.random(), random.random())
        x, y = d.x(), d.y()
        d.set_x(y)
        d.set_y(x)
        iterations -= 1

if __name__ == '__main__':
    from sys import argv, stdout
    if len(argv) > 1:
        iterations = long(argv[1])
    else:
        iterations = 100000

    print 'Performing %d iterations without Psyco' % iterations
    stdout.flush()
    start = time.time()
    test_class(iterations)
    end = time.time()
    print '* Done'
    print "That took %.3f seconds" % (end - start)
    print
    import psyco
    psyco.bind(Dot)
    psyco.bind(test_class)
    print 'Performing %d iterations with Psyco' % iterations
    stdout.flush()
    start = time.time()
    test_class(iterations)
    end = time.time()
    print '* Done'
    print "That took %.3f seconds" % (end - start)
#----class_test.py--------

produces this output:

$ python psyco-test.py
Performing 100000 iterations without Psyco
* Done
That took 1.985 seconds

Performing 100000 iterations with Psyco
* Done
That took 1.198 seconds
$

That's a lot easier than rewriting all your code...

Tim C






More information about the Python-list mailing list