Performance penalty for using classes?

Miki Tebeka tebeka at cs.bgu.ac.il
Sun Jan 12 09:04:43 CET 2003


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

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

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 'Going %d iterations' % iterations
    stdout.flush()
    test_class(iterations)
    print '* Done'
--- class_test.py ---

---- struct_test.py ---#!/usr/bin/env python

import random

def make_dot(x, y):
    return [x, y]

def dot_x(dot):
    return dot[0]

def dot_set_x(dot, x):
    dot[0] = x

def dot_y(dot):
    return dot[1]

def dot_set_y(dot, y):
    dot[1] = y


def test_struct(iterations):
    while iterations > 0:
        d = make_dot(random.random(), random.random())
        x, y = dot_x(d), dot_y(d)
        dot_set_x(d, y)
        dot_set_y(d, x)
        iterations -= 1


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

    print 'Going %d iterations' % iterations
    stdout.flush()
    t = test_struct(iterations)
    print '* Done'
--- struct-test.py ---

[10:02] $time class_test.py 
Going 100000 iterations
* Done
real 5.43
user 5.27
sys 0.02
[10:02] $time struct_test.py 
Going 100000 iterations
* Done
real 4.27
user 4.22
sys 0.00




More information about the Python-list mailing list