timeit函数内的IndentationError

问题描述 投票:0回答:1

我想测量部分代码的处理时间,为此使用了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
1个回答
0
投票

执行缩进的两种方法是使用空格(标准规范是对一个级别的缩进使用4个空格),或使用制表符。确保没有混合它们。坚持其中之一。

如果您可以将我的代码作为.py文件共享给我,我可能会通过确切地说明问题来为您提供更多帮助。

© www.soinside.com 2019 - 2024. All rights reserved.