這個問題在這里已經有了答案: Python 型別提示(注釋)是否會導致一些運行時影響?[重復] (2個答案) 3天前關閉。
這些是我在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
I know theorically there should not be any difference in list or int annotations, while there is no functionality regarding to them. But I just tested these types to make sure that using type hints slows down the execution by about 25 percent. Why is this? As far as I know type hints do nothing with executing. Just spending more time to parse them and adding them to the __annotations__ dictionary makes this huge difference in execution time?
uj5u.com熱心網友回復:
您的方法是測驗將 python 代碼的原始字串版本解釋為可執行檔案的編譯時間。如果您將 timeit 與 fucntions 一起使用,您不會看到明顯的差異:
import timeit
def method1():
for _ in range(1000): a: int = 4
def method2():
for _ in range(1000): a = 4
print(timeit.timeit(method1, number=200000))
print(timeit.timeit(method2, number=200000))
2.8046581
2.8103205999999994
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/447854.html
