This is my first post of a list about python performance and how to achieve it. My first post is about global variables. I don’t advise global variables except in few cases, reasons are multiples, but in case you have to use them, take into account this little test:
from profileit import profileit globalVar = 0 cycles = 1000000 @profileit(0) def globalTest (): global globalVar for i in range (cycles): globalVar += 1 # Local instead global search @profileit(0) def localTest (): global globalVar localVar = globalVar for i in range (cycles): localVar += 1 globalVar = localVar if __name__ == '__main__': globalTest () localTest ()
This test uses my dear profileit decorator to measure time of functions. You can see a couple of global variable, globalVar will be my main variable and cycles that is only for iteration purpose. In the first function, you see a simple loop that adds one to the global variable, this implies a read and a write of the variable in the global scope. These reads ans writes are expensive because python interpreter must look for the variable in the local scope and then in the global scope.
But in the second case, you can see that globalVar comes to local scope in the localVar variable. This implies one and only one read and write instead of 1.000.000 reads/writes. And in the second function also, you have always local variable look up of the interpreter. So, the results are:
*** <function globalTest at 0x00B7C9B0>
>>>---- Begin profiling print
1 function calls in 1.186 CPU seconds
>>>---- End profiling print
*** <function localTest at 0x00B7CA30>
>>>---- Begin profiling print
1 function calls in 1.024 CPU seconds
>>>---- End profiling print
This means about a 16% of difference. This is a huge advance in performance terms, and this is a dummy example. Imagine how much time you can save in a real case!
TIP: Always bring global variables to local scope, and when I say variables I’m also saying built-in functions and anything at global scope intensively used in the function.
This is all for now. Comments welcomed.