【发布时间】:2019-11-04 05:59:22
【问题描述】:
我想测量部分代码的处理时间,为此我使用了 timeit 函数。但是它从 timeit 函数内部返回 IndentationError。
这是我的代码;
for stem, result in zip(stem_dirs, result_dirs):
code_to_measure = '''
print(stem, '\n', result)
subprocess.call(['python', './a.py', "--dir_in", stem, "--dir_out", result])
'''
proccess_time = timeit.timeit(code_to_measure)
print(proccess_time)
这是我得到的错误;
Traceback (most recent call last):
File "code_test.py", line 115, in <module>
proccess_time = timeit.timeit(code_to_measure)
File "/usr/local/lib/python3.6/timeit.py", line 233, in timeit
return Timer(stmt, setup, timer, globals).timeit(number)
File "/usr/local/lib/python3.6/timeit.py", line 123, in __init__
compile(stmtprefix + stmt, dummy_src_name, "exec")
File "<timeit-src>", line 3
print(stem, '
^
IndentationError: unexpected indent
但是,下面代码中的timeit函数仍然可以正常运行;
# importing the required module
import timeit
# code snippet to be executed only once
mysetup = "from math import sqrt"
# code snippet whose execution time is to be measured
mycode = '''
def example():
mylist = []
for x in range(100):
mylist.append(sqrt(x))
'''
# timeit statement
print(timeit.timeit(setup = mysetup,
stmt = mycode,
number = 10000))
这是代码的输出;
0.002189640999858966
我不太确定如何解决这个问题。如果您对此问题有任何建议或解决方案,请告诉我。
非常感谢您。
【问题讨论】:
标签: python-3.x subprocess timeit