How many function calls does it take to instantiate a class?

Knowing that calling a function in python is expensive, the answer to this question has something to do with optimization solutions, for example. in comparing a direct single-functional numerical approach to an object-oriented one. Therefore i would like to know

  • What is the typical number of function calls required?
  • What is the minimum number of function calls required?
  • What increases the number of calls?
  • How do user-created classes compare with built-in classes?
  • How about deleting an object (including garbage collection)?

My google-fu failed to find the answer to this question.

EDIT: So, to summarize the comments and warn closer voices, here are some clarifications:

  • I am interested in the python instance creation time complexity compared to calling a normal python function.
  • For the purposes of this question, let me limit myself to the latest versions of CPython.
+5
source share
2 answers

See Creating Python Objects from Eli Bendersky.

In conclusion, we conclude in detail:

So that we do not lose the forest for trees, let's look at this issue again. The article began with. What happens when CPython executes j = Joe()?

  • Since it Joedoes not have an explicit metaclass, typeits type. Thus, the tp_callslot typethat is type_callcalled is called.
  • type_callstarts with calling tp_newJoe slot :
    • Joe , object. object_new.
    • Joe , Python, tp_alloc. object_new PyType_GenericAlloc.
    • PyType_GenericAlloc , , Joe.
  • type_call Joe.__init__ .
    • Joe __init__, __init__ , object_init.
    • object_init .
  • type_call j.
+7

, , timeit :

def a():
    pass

class A(object):
    pass

class B(object):
    def __init__(self):
        pass

class NOPType(type):
    pass

class C(object):
    __metaclass__ = NOPType
    def __init__(self):
        pass

class D(object):
    def __new__(cls, *args, **kwargs):
        return super(D, cls).__new__(cls)

    def __init__(self):
        pass

class E(A):
    def __init__(self):
        super(E, self).__init__()

:

$ python -m timeit -s "import tst" "tst.a()"
10000000 loops, best of 3: 0.149 usec per loop
$ python -m timeit -s "import tst" "tst.A()"
10000000 loops, best of 3: 0.169 usec per loop
$ python -m timeit -s "import tst" "tst.B()"
1000000 loops, best of 3: 0.384 usec per loop
$ python -m timeit -s "import tst" "tst.C()"
1000000 loops, best of 3: 0.397 usec per loop
$ python -m timeit -s "import tst" "tst.D()"
1000000 loops, best of 3: 1.09 usec per loop
$ python -m timeit -s "import tst" "tst.E()"
1000000 loops, best of 3: 0.827 usec per loop

, :

  • 1,1 .
  • __init__ 2.6
  • - no-op - , 2.7.
  • __new__, 7.3
  • 5,6

2, super .

, python python, CPython 2.7.

+3

All Articles