2

So, I have a script with a lot of debugging output that I can toggle on/off with a -v flag. My current code looks like this:

def vprint( obj ):
    if args.verbose:
        print obj

However, I'm thinking this is inefficient since every time I call vprint(), it has to jump to that function and check the value of args.verbose. I came up with this, which should be slightly more efficient:

if args.verbose:
    def vprint( obj ):
        print obj
else:   
    def vprint( obj ):
        pass

While the if is now removed, it still has to jump to that function. So I was wondering if there was a way to define vprint as something like a function pointer that goes nowhere, so it could skip that altogether? Or is Python smart enough to know not to waste time on a function that's just pass?

4

1 回答 1

4

Unless your performance analysis has lead you here, it's probably not worth optimizing. A quick set of tests yields a minor (0.040) improvement over 1000000 iterations:

         1000004 function calls in 0.424 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.424    0.424 <string>:1(<module>)
        1    0.242    0.242    0.424    0.424 test.py:14(testit)
        1    0.000    0.000    0.424    0.424 test.py:21(testit1)
  1000000    0.182    0.000    0.182    0.000 test.py:6(vprint)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


         1000004 function calls in 0.408 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.408    0.408 <string>:1(<module>)
  1000000    0.142    0.000    0.142    0.000 test.py:10(vprint2)
        1    0.266    0.266    0.408    0.408 test.py:14(testit)
        1    0.000    0.000    0.408    0.408 test.py:18(testit2)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Test code follows;

#!/usr/bin/python

import cProfile

verbose=False
def vprint(msg):
    if verbose:
        print msg

def vprint2(msg):
    pass

def testit(fcn):
    for i in xrange(1000000):
        fcn(i)

def testit2():
    testit(vprint2)

def testit1():
    testit(vprint)

if __name__ == '__main__':
    cProfile.run('testit1()')
    cProfile.run('testit2()')
于 2013-02-19T20:36:36.510 回答