2

そのため、-v フラグでオン/オフを切り替えることができる多くのデバッグ出力を含むスクリプトがあります。私の現在のコードは次のようになります。

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

ただし、 を呼び出すたびにvprint()、その関数にジャンプして の値をチェックする必要があるため、これは非効率的だと思いますargs.verbose。私はこれを思いつきました。これは少し効率的であるはずです:

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

は削除されましたifが、その関数にジャンプする必要があります。vprintそれで、どこにも行かない関数ポインターのようなものとして定義する方法があるかどうか疑問に思っていたので、それを完全にスキップできますか? それとも、Python はただの関数で時間を無駄にしないことを知っているほど賢いのpassでしょうか?

4

1 に答える 1

4

パフォーマンス分析によってここにたどり着かない限り、おそらく最適化する価値はありません。簡単な一連のテストでは、1000000 回の反復でマイナー (0.040) の改善が得られます。

         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}

テスト コードは次のとおりです。

#!/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 に答える