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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With