【问题标题】:IndentationError within the timeit functiontimeit 函数内的 IndentationError
【发布时间】: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


    【解决方案1】:

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

    如果您可以将您的代码以 .py 文件的形式与我分享,我或许可以通过准确告诉您问题所在来为您提供更多帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      相关资源
      最近更新 更多