这是我ipython
年的测试结果.
int
美元:
In [2]: %time for _ in range(1000): exec('a: int = 4')
CPU times: user 12.2 ms, sys: 12 µs, total: 12.2 ms
Wall time: 12.2 ms
In [3]: %time for _ in range(1000): exec('a = 4')
CPU times: user 9.5 ms, sys: 0 ns, total: 9.5 ms
Wall time: 9.54 ms
str
美元:
In [4]: %time for _ in range(1000): exec('a: str = "hello"')
CPU times: user 13.3 ms, sys: 0 ns, total: 13.3 ms
Wall time: 13.4 ms
In [5]: %time for _ in range(1000): exec('a = "hello"')
CPU times: user 10.4 ms, sys: 0 ns, total: 10.4 ms
Wall time: 10.4 ms
list
美元:
In [6]: %time for _ in range(1000): exec('a: list = [1,2, "hello"]')
CPU times: user 19.1 ms, sys: 0 ns, total: 19.1 ms
Wall time: 21.5 ms
In [7]: %time for _ in range(1000): exec('a = [1,2, "hello"]')
CPU times: user 15.8 ms, sys: 0 ns, total: 15.8 ms
Wall time: 15.8 ms
我知道理论上list
或int
个注释应该没有任何区别,但它们没有任何功能.但我只是测试了这些类型,以确保使用类型提示会将执行速度降低约25%.这是为什么?据我所知,类型提示与执行无关.只是花更多的时间来解析它们,并将它们添加到__annotations__
字典中,就可以在执行时间上产生如此巨大的差异?