Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a function/method call in python expensive?

Tags:

In this post, Guido van Rossum says that a function call may be expensive, but I do not understand why nor how much expensive can be.

How much delay adds to your code a simple function call and why?

like image 946
VGonPa Avatar asked Apr 06 '14 11:04

VGonPa


People also ask

Why are function calls expensive in Python?

Main reason for the large function call overhead in Python is the “boxing” and “unboxing” of function call arguments and return values. Once again, dynamic typing makes programming more flexible but with a cost in performance.

Is function call expensive?

Speaking from personal experience, I write code in a proprietary language that is fairly modern in terms of capability, but function calls are ridiculously expensive, to the point where even typical for loops have to be optimized for speed: for(Integer index = 0, size = someList.

Is calling functions in Python slow?

The short version is that it takes about 150ns to call a function in Python (on my laptop). This doesn't sound like a lot, but it means that you can make at most 6.7 million calls per second, two to three orders of magnitude slower than your processor's clock speed.

What is the purpose of calling a function in Python?

Functions can be called anywhere and the number of times in a program. It allows us to reuse the code by simply calling the particular function or block in a program. Thus, it avoids the repetition of the same code.


1 Answers

A function call requires that the current execution frame is suspended, and a new frame is created and pushed on the stack. This is relatively expensive, compared to many other operations.

You can measure the exact time required with the timeit module:

>>> import timeit >>> def f(): pass ...  >>> timeit.timeit(f) 0.15175890922546387 

That's 1/6th of a second for a million calls to an empty function; you'd compare the time required with whatever you are thinking of putting in a function; the 0.15 second would need to taken into account, if performance is an issue.

like image 57
Martijn Pieters Avatar answered Nov 05 '22 23:11

Martijn Pieters