A better self

Delaney, Timothy tdelaney at avaya.com
Mon Jul 22 19:12:06 EDT 2002


> From: Louis M. Pecora [mailto:pecora at anvil.nrl.navy.mil]
> 
> What's the overhead of the function calls versus either
> 
> (1) t, x, y, z=self.t, self.x, self.y, self.z
> 
> or
> 
> (2)t=self.t;   x=self.x;   y=self.y;   z=self.z; 
> 
> ??
> 
> Seems like (1) and (2) have less overhead and someone in this thread
> said (1) creates and then destroys a tuple (unnecessarily so) and (2)
> is better (no intermediate tuple). 
> 
> I still prefer (1) -- most readable, but I like minimum overhead.

Do some profiling ... (untested code follows)

---

import time

class Vars:

    def __init__(self):
        self.t = 1
        self.x = 2
        self.y = 3
        self.z = 4

def f (t, x, y, z):
    pass

def bench (f=f, time=time): # to remove global lookups

    r = range(1000000) # modify as required to get usable times
    v = Vars()

    start = time.clock()
    for i in r:
        t, x, y, z = v.t, v.x, v.y, v.z
    end = time.clock()
    print (end - start)

    start = time.clock()
    for i in r:
        t = v.t
        x = v.x
        y = v.y
        z = v.z
    end = time.clock()
    print (end - start)

    start = time.clock()
    for i in r:
        f(v.t, v.x, v.y, v.z)
    end = time.clock()
    print (end - start)

if __name__ == '__main__':
    bench()

---

On my machine, the results are:

2.30967285289
2.14318686404
2.982054833

This is *purely* the overhead of the various function call, tuple packing
and unpacking, etc - once you start doing things with these they start
having much less effect (because you're only using local variables in each
case).

Tim Delaney





More information about the Python-list mailing list