如何timeit.timeit多行输出无EOL错误?

How to timeit.timeit multi-line output without EOL error?

我将以下代码存储在 .py 文件中:

input1 = ["2",
          "0 0 1 1 small",
          "3 2 6 5 large",
          "3",
          "2 0 small",
          "0.5 0.6 medium",
          "3 4 large",
          "3",
          "60.0 2.9 111.4 32.9 medium",
          "20.0 82.6 43.4 153.1 small",
          "34.7 9.6 56.6 78.2 large",
          "6",
          "60.0 8.3 small",
          "43.4 153.1 small",
          "13.4 55.9 medium",
          "61.5 68.1 medium",
          "72.1 69.1 large",
          "78.4 13.2 large",
          "0"]

nm = []
peanut_descriptions = []
box_descriptions = []

for line in input1:
    next_line_index = input1.index(line)+1
    parsed_line = line.split()


    # number of box/peanut descriptions for each case
    if len(parsed_line) == 1:
        if int(parsed_line[0]) == 0:
            break
        parsed_next_line = input1[next_line_index].split()
        nm.append(int(parsed_line[0]))


    # identify peanut descriptions
    if len(parsed_line) == 3:
        peanut_description_dict = {'x': parsed_line[0],
                                   'y': parsed_line[1],
                                   'peanut_size': parsed_line[2]}
        peanut_descriptions.append(peanut_description_dict)


    # identify box descriptions
    if len(parsed_line) == 5:
        box_description_dict = {'x1': parsed_line[0],
                                'y1': parsed_line[1],
                                'x2': parsed_line[2],
                                'y2': parsed_line[3],
                                'intended_size': parsed_line[4]}
        box_descriptions.append(box_description_dict)
    previous_line = line


# peanut sizes
peanut_sizes = []
for i in peanut_descriptions:
    peanut_size = i['peanut_size']
    peanut_sizes.append(peanut_size)

# cases
cases = []
for i in range(len(nm)):
    if i % 2 != 0:
        continue
    boxes_index = nm[i]
    peanuts_index = nm[i+1]

    boxes_case = box_descriptions[0:boxes_index]
    peanuts_case = peanut_descriptions[0:peanuts_index]

    case = [boxes_case, peanuts_case]
    cases.append(case)

    del box_descriptions[0:boxes_index]
    del peanut_descriptions[0:peanuts_index]

# matching
matched_boxes = []
matched_peanuts = []
statuses = []
all_statuses = []
for case_index in range(len(cases)):
    case = cases[case_index]
    box = case[0]
    peanut = case[1]
    statuses = []
    for p in range(len(peanut)):
        status = "floor"
        for b in range(len(box)):
            p_x = float(peanut[p]['x'])
            p_y = float(peanut[p]['y'])
            peanut_size = peanut[p]['peanut_size']
            b_x1 = float(box[b]['x1'])
            b_y1 = float(box[b]['y1'])
            b_x2 = float(box[b]['x2'])
            b_y2 = float(box[b]['y2'])
            box_category = box[b]['intended_size']
            values1 = (p_x, p_y, peanut_size, b_x1, b_y1, b_x2, b_y2, box_category)
            if b_x1 <= p_x <= b_x2 and b_y1 <= p_y <= b_y2:
                final_box = box[b]["intended_size"]
                status = final_box
            # print(values1)

            if peanut_size == box_category and status == box[b]["intended_size"]:
                status = "correct"
            # values1 = {"p_x": p_x, "p_y": p_y, "b_x1": b_x1, "b_y1": b_y1, "b_x2": b_x2, "b_y2": b_y2}
            # print(values1)
        statuses.append(status)

    all_statuses.append(statuses)
    matched_boxes = []
    matched_peanuts = []


# # final answer:
output1 = []
statuses1 = []
for i in range(len(all_statuses)):
    case_statuses = all_statuses[i]
    paragraph = ""
    for j in range(len(case_statuses)):
        line = peanut_sizes[j] + " " + case_statuses[j] + "\n"
        paragraph += line
    output1.append(paragraph)
    del peanut_sizes[0:len(case_statuses)]
    statuses1.append(case_statuses)
    case_statuses = []
output1 = "\n".join(output1)

print(output1)

这段代码执行得非常好。但是现在我想测量执行代码所花费的时间。所以我尝试通过以下方式将其插入 timeit.timeit:

import timeit
test1 = """
# copy+paste the above code here
"""
print(timeit.timeit(test1, number=100))

现在我收到以下错误:

    line = peanut_sizes[j] + " " + case_statuses[j] + "
                                                      ^
SyntaxError: EOL while scanning string literal

很明显,python 代码似乎给我 EOL 错误,因为我在最后一个引用之前放了 \n。但是在我试图解决的问题中,我确实需要在特定模式中包含多行(包括空行),作为最终输出的一部分,并且它需要为各种各样的多行自动创建这些空行-线路输入。

input1 是实际输入的修改版本,这样我可以更清楚地看到编码时发生了什么。实际输入将与 input1 相同,只是它是一个文件对象而不是列表,并且会有一个换行符而不是逗号。我的代码将该文件对象转换为您在代码中看到的 input1 列表。

那么如何timeit.timeit 上面代码的多行输出没有 EOL 错误?

你可以用timeit调用一个函数

def a_function(some_inputs):
    outputs1 = do_some_crazy_stuff(some_inputs)
    outputs2 = do_some_more_crazy_stuff(outputs1)
    return some_really_crazy_stuff(outputs2)

timeit.timeit(lambda: a_function(my_input_test), number=10)

但是您的实际问题只是格式错误的代码...它打开一个字符串并且永远不会关闭它

你需要将"\n"转义为"\n",否则你的\n会被逐字计算为

my_var = asd + " " + dsa + "
"

这是未终止字符串文字的语法错误