Why is creating a class in Python so much slower than instantiating a class?

前端 未结 4 1242
谎友^
谎友^ 2021-01-31 17:33

I found that creation of a class is way slower than instantiation of a class.

>>> from timeit import Timer as T
>>> def calc(n):
...     return         


        
4条回答
  •  天涯浪人
    2021-01-31 17:47

    Ahahaha! Gotcha!

    Was this perchance done on a Python version without this patch? (HINT: IT WAS)

    Check the line numbers if you want proof.

    Marcin was right: when the results look screwy you've probably got a screwy benchmark. Run gc.disable() and the results reproduce themselves. It just shows that when you disable garbage collection you get garbage results!


    To be more clear, the reason running the long benchmark broke things is that:

    • timeit disables garbage collections, so overly large benchmarks take much (exponentially) longer

    • timeit wasn't restoring garbage collection on exceptions

    • You quit the long-running process with an asynchronous exception, turning off garbage collection

提交回复
热议问题