【问题标题】:Python: Most efficient way to toggle "verbose" output?Python:切换“详细”输出的最有效方法?
【发布时间】:2013-02-19 19:55:51
【问题描述】:

所以,我有一个包含大量调试输出的脚本,我可以使用 -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 的函数上浪费时间?

【问题讨论】:

  • 您可能想看看logging 模块。

标签: python logging function-pointers


【解决方案1】:

除非您的性能分析将您带到这里,否则可能不值得优化。与 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()')

【讨论】:

  • 有趣的是,虽然循环时间增加了 0.040,但 testit 的总时间只增加了 0.022。
猜你喜欢
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 2014-01-08
  • 1970-01-01
  • 2015-04-27
相关资源
最近更新 更多