开发者

Will using less calls to functions increase speed of total execution? [duplicate]

开发者 https://www.devze.com 2023-03-02 09:26 出处:网络
This question already has answers here: 开发者_运维技巧 Closed 11 years ago. Possible Duplicate:
This question already has answers here: 开发者_运维技巧 Closed 11 years ago.

Possible Duplicate:

Does creating separate functions instead of one big one slow processing time?

OOP Bloop boop!

Yes, OOP is great, keeps code clean and well organized. That's why I like to use it. I"m referring to to OOP very primitively specifically in using functions (defs).

Will taking out my function calls and sticking the content of the function straight into my algo increase speed of execution of the overall code? Yes, I know I can run a test myself, but I'm choosing to ask it here in the forum of my fellow coder colleagues, because I know this is a question that floats around in many heads....

def myFunc(var):
   return var*3243 #perhaps more complicated function code will make a difference?

i = 0
hungry = True
while hungry:
  i = i + 1
  x = myFunc(i)
  if i > 50:
     hungry = False


Write it correctly (i.e. with concerns properly separated into distinct functions and classes), then use PyPy to make it fast.

PyPy uses function inlining and assorted other tricks in its Just-In-Time compiler to speed up code execution without having to make it unmaintainable in the name of speed.

Note that this solution only works if you're using the Python 2.x series with any C extensions you use being compatible with cpyext.


Apparently there is very high function call overhead in Python.

http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Data_Aggregation

Is it worth keeping in mind while choosing the best way to write a piece of code?
Sure.
Is the speed up worth making your coder harder to understand?
Probably not.


Python won't "inline" the function for you, so of course there is overhead. Usually the code in the function will take enough time that the call overhead is not significant.

Bear in mind that it's much easier to test,debug and profile programs that are broken up into functions.

If you really really need more performance it's usually a better idea to write the function in C or Cython than to eliminate the call overhead

It's also worth noting that the usual code set up like this

def main():
   ...

if __name__=="main":
    main()

is faster than just running code at the top level as identifier lookups are faster in functions/methods than in the global namespace

0

精彩评论

暂无评论...
验证码 换一张
取 消