why a main() function?
Peter Otten
__peter__ at web.de
Tue Sep 19 08:00:48 EDT 2006
Diez B. Roggisch wrote:
> bearophileHUGS at lycos.com wrote:
>
>> Others have already told you the most important things.
>>
>> There is another secondary advantage: the code inside a function runs
>> faster (something related is true for C programs too). Usually this
>> isn't important, but for certain programs they can go 20%+ faster.
>
> I totally fail to see why that should be the case - for python as well as
> for C.
>
> So - can you explain that a bit more, or provide resources to read up on
> it?
A trivial example (for Python):
$ cat main.py
def main():
x = 42
for i in xrange(1000000):
x; x; x; x; x; x; x; x; x; x
x; x; x; x; x; x; x; x; x; x
x; x; x; x; x; x; x; x; x; x
main()
$ time python main.py
real 0m0.874s
user 0m0.864s
sys 0m0.009s
$ cat nomain.py
x = 42
for i in xrange(1000000):
x; x; x; x; x; x; x; x; x; x
x; x; x; x; x; x; x; x; x; x
x; x; x; x; x; x; x; x; x; x
$ time python nomain.py
real 0m2.154s
user 0m2.145s
sys 0m0.009s
$
Now let's verify that global variables are responsible for the extra time:
$ cat main_global.py
def main():
global i, x
x = 42
for i in xrange(1000000):
x; x; x; x; x; x; x; x; x; x
x; x; x; x; x; x; x; x; x; x
x; x; x; x; x; x; x; x; x; x
main()
$ time python main_global.py
real 0m2.002s
user 0m1.995s
sys 0m0.007s
Peter
More information about the Python-list
mailing list