Python Match Case(开关)性能

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

我原本期望 Python

match
/
case
对每个案例都有相同的时间访问权限,但似乎我错了。有什么好的解释吗?

让我们使用以下示例:

def match_case(decimal):
    match decimal:
      case '0':
        return "000"
      case '1':
        return "001"
      case '2':
        return "010"
      case '3':
        return "011"
      case '4':
        return "100"
      case '5':
        return "101"
      case '6':
        return "110"
      case '7':
        return "111"
      case _:
        return "NA"

并定义一个快速工具来测量时间:

import time
def measure_time(funcion):
    def measured_function(*args, **kwargs):
        init = time.time()
        c = funcion(*args, **kwargs)
        print(f"Input: {args[1]} Time: {time.time() - init}")
        return c
    return measured_function

@measure_time
def repeat(function, input):
    return [function(input) for i in range(10000000)]

如果我们对每个案例运行

10000000
次,则时间如下:

for i in range(8):
    repeat(match_case, str(i))

# Input: 0 Time: 2.458001136779785
# Input: 1 Time: 2.36093807220459
# Input: 2 Time: 2.6832823753356934
# Input: 3 Time: 2.9995620250701904
# Input: 4 Time: 3.5054492950439453
# Input: 5 Time: 3.815168857574463
# Input: 6 Time: 4.164452791213989
# Input: 7 Time: 4.857251167297363

只是想知道为什么访问时间不同。这不是通过查找表进行优化的吗?请注意,我对具有相等访问时间的其他方式(即使用字典)不感兴趣。

python python-3.x switch-statement match
1个回答
8
投票

PEP 622 “比赛

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