sarmin kho wrote:
Hi Pythoners,
i have been using a lot of global variables in the python script i am
working on. the global variables are shared and used by all various
'definitions' :
def name ():
global all globs...
.....
my question is: 'is it safe using global variables in term of its
execution time?
Here is may attempt to measure it:
<time_global.py>
def f():
x = 1
x
x
x
x
x
x
x
x
x
x
def g():
global x
x = 1
x
x
x
x
x
x
x
x
x
x
</time_global.py>
$ timeit.py -s"from time_global import f" "f()"
1000000 loops, best of 3: 0.972 usec per loop
$ timeit.py -s"from time_global import g" "g()"
1000000 loops, best of 3: 1.13 usec per loop
If the methodology isn't flawed, the effect is hardly noticable, as a real
function will have other operations that take much longer than a variable
lookup.
i cant think of any other ways not to use the globs because some variables
simply have to be shared among those definitions..
For a one-off script I see no problem, but otherwise I'd suggest you think
again and stay away from global variables as much as possible; the cost in
maintenance time may by far eclipse the extra execution time.
As a dumb "better than nothing" recipe I suggest you bundle the globals in a
Bunch-like class and pass that explicitly to your functions, or convert the
functions into methods and keep the "global" state as instance attributes.
Peter