gpt4 book ai didi

Python Match Case (Switch) 性能

转载 作者:行者123 更新时间:2023-12-04 07:21:25 33 4
gpt4 key购买 nike

我期待 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
只是想知道为什么访问时间不同。这不是用查找表优化的吗?。请注意,我对具有相等访问时间的其他方式(即使用字典)不感兴趣。

最佳答案

PEP 622
开发了“match\case”功能来替换这样的代码:

def is_tuple(node):
if isinstance(node, Node) and node.children == [LParen(), RParen()]:
return True
return (isinstance(node, Node)
and len(node.children) == 3
and isinstance(node.children[0], Leaf)
and isinstance(node.children[1], Node)
and isinstance(node.children[2], Leaf)
and node.children[0].value == "("
and node.children[2].value == ")")
用这样的代码:
def is_tuple(node: Node) -> bool:
match node:
case Node(children=[LParen(), RParen()]):
return True
case Node(children=[Leaf(value="("), Node(), Leaf(value=")")]):
return True
case _:
return False
虽然在最原始的情况下它可能等效于 dict 查找,但通常并非如此。案例模式被设计成看起来像普通的 Python 代码,但实际上它们隐藏了 isinsancelen当您看到类似 Node() 的代码时,不要执行您期望执行的操作。 .

Essentially this is equivalent to a chain of if ... elif ... else statements. Note that unlike for the previously proposed switch statement, the pre-computed dispatch dictionary semantics does not apply here.

关于Python Match Case (Switch) 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68476576/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com