Python function implementation

I saw various answers to the ball collision detection question explaining why sqrt operations are slow, why absolute operations are fast on floating point, etc. How to find out which operations are expensive and which are not?

Basically, I'm looking for a resource where I can find out about the implementation of all the functions of the python library. When people say these things, they don’t really think about how it is implemented in C?

Thank you, wanting to know more about the details of the implementation of this language.

+3
source share
4 answers

Python, , . , .

, Python - .

!

EDIT: , : ? , .

+1

Python , .

+1

, , timeit.

, , , :

python -m timeit -s 'import math; x = 42.5; y = 17.2; r = 50.0' 'math.sqrt(x**2 + y**2) <= r'
python -m timeit -s 'import math; x = 42.5; y = 17.2; r = 50.0' 'math.hypot(x, y) <= r'
python -m timeit -s 'import math; x = 42.5; y = 17.2; r = 50.0' 'x**2 + y**2 <= r**2'

:

$ python -m timeit -s 'import math; x = 42.5; y = 17.2; r = 50.0' 'math.sqrt(x**2 + y**2) <= r'
1000000 loops, best of 3: 0.744 usec per loop
$ python -m timeit -s 'import math; x = 42.5; y = 17.2; r = 50.0' 'math.hypot(x, y) <= r'
1000000 loops, best of 3: 0.374 usec per loop
$ python -m timeit -s 'import math; x = 42.5; y = 17.2; r = 50.0' 'x**2 + y**2 <= r**2'
1000000 loops, best of 3: 0.724 usec per loop

math.hypot ! , , :

$ python -m timeit -s 'from math import hypot; x = 42.5; y = 17.2; r = 50.0' 'hypot(x, y) <= r'
1000000 loops, best of 3: 0.334 usec per loop
+1

Python :

>>> def foo(): print
... 
>>> import dis
>>> dis.dis(foo)
  1           0 PRINT_NEWLINE       
              1 LOAD_CONST               0 (None)
              4 RETURN_VALUE        

:

>>> from math import sqrt
>>> import dis
>>> dis.dis(sqrt)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/dis.py", line 48, in dis
    type(x).__name__
TypeError: don't know how to disassemble builtin_function_or_method objects
0

Source: https://habr.com/ru/post/1753951/


All Articles