我想在同一个Python模块中编写多个函数,每个函数都使用timeit
进行单独的性能分析测试,这样我就可以使用命令行参数来指定要运行的那个。一个简单的例子(profiling.py)将是:
import sys
import timeit
def foo():
setup = """
import random
"""
foo_1 = """
for i in range(1000):
random.randint(0, 99) + random.randint(0, 99)
"""
foo_2 = """
for i in range(1000):
random.randint(0, 99) + random.randint(0, 99)
"""
foo_3 = """
for i in range(1000):
random.randint(0, 99) + random.randint(0, 99)
"""
print 'foo_1', timeit.Timer(foo_1, setup).timeit(1000)
print 'foo_2', timeit.Timer(foo_2, setup).timeit(1000)
print 'foo_3', timeit.Timer(foo_3, setup).timeit(1000)
if __name__ == '__main__':
if (len(sys.argv) > 1):
if (sys.argv[1] == 'foo'):
foo()
else:
print 'Which profiling do you want to run?'
print 'available:'
print ' foo'
但是,当我尝试python profiling.py foo
时,我会收到如下错误:
foo_1
Traceback (most recent call last):
File "profiling.py", line 32, in <module>
foo()
File "profiling.py", line 25, in foo
print 'foo_1', timeit.Timer(foo_1, setup).timeit(1000)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/timeit.py", line 136, in __init__
code = compile(src, dummy_src_name, "exec")
File "<timeit-src>", line 6
_t0 = _timer()
^
IndentationError: unindent does not match any outer indentation level
我在代码中搜索了通常的空格/制表符缩进错误,但没有找到任何错误。因此我想知道是不是因为我在函数中包含timeit
测试,这是不允许的?
答案 0 :(得分:7)
这有效:
import sys
import timeit
def foo():
setup = """
import random
"""
foo_1 = """
for i in range(1000):
random.randint(0, 99) + random.randint(0, 99)
"""
foo_2 = """
for i in range(1000):
random.randint(0, 99) + random.randint(0, 99)
"""
foo_3 = """
for i in range(1000):
random.randint(0, 99) + random.randint(0, 99)
"""
print 'foo_1', timeit.Timer(foo_1, setup).timeit(1000)
print 'foo_2', timeit.Timer(foo_2, setup).timeit(1000)
print 'foo_3', timeit.Timer(foo_3, setup).timeit(1000)
if __name__ == '__main__':
if (len(sys.argv) > 1):
if (sys.argv[1] == 'foo'):
foo()
else:
print 'Which profiling do you want to run?'
print 'available:'
print ' foo'
问题是,您传递为setup
和foo_1
等等的字符串是缩进的,因为您已经将它们与缩进的代码排列在一起功能。但是,当该字符串由timeit
执行时,它会引发您看到的缩进错误,因为代码不应缩进。如果您尝试过这种情况,情况基本相同......
exec(" import sys")
作为交互式翻译会话中的第一件事。
答案 1 :(得分:0)
你可以通过单独写行并加入它们来获得相同的效果,如下所示:
import sys
import timeit
def foo():
setup = 'import random'
foo_1 = '\n'.join([
'for i in range(1000):',
' random.randint(0, 99) + random.randint(0, 99)',
])
foo_2 = '\n'.join([
'for i in range(1000):',
' random.randint(0, 99) + random.randint(0, 99)',
])
foo_3 = '\n'.join([
'for i in range(1000):',
' random.randint(0, 99) + random.randint(0, 99)',
])
print 'foo_1', timeit.Timer(foo_1, setup).timeit(1000)
print 'foo_2', timeit.Timer(foo_2, setup).timeit(1000)
print 'foo_3', timeit.Timer(foo_3, setup).timeit(1000)
if __name__ == '__main__':
if (len(sys.argv) > 1):
if (sys.argv[1] == 'foo'):
foo()
else:
print 'Which profiling do you want to run?'
print 'available:'
print ' foo'
你在每一行上获得的空间更少,但我的权衡对我来说是值得的。