Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do type annotations make Python code slower? [duplicate]

These are results of my tests in ipython.

For 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

And for 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

And also for 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?

like image 444
Amir reza Riahi Avatar asked Jun 21 '26 07:06

Amir reza Riahi


1 Answers

Your method is testing the compilation time of interpreting the raw string version of the python code into something that is executable. If you were to instead use timeit with fucntions, you wouldn't see a noticeable difference:

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
like image 60
flakes Avatar answered Jun 22 '26 20:06

flakes