Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
1 view
by (47.6k points)

def main():

for i in xrange(10**8):

pass main()

This piece of code in Python runs in (Note: The timing is done with the time function in BASH in Linux.)

real 0m1.841s 

user 0m1.828s 

sys  0m0.012s

However, if the for loop isn't placed within a function,

for i in xrange(10**8): 

pass

then it runs for a much longer time:

real 0m4.543s 

user 0m4.524s 

sys 0m0.012s

Why is this?

1 Answer

0 votes
by (106k points)

The reason for a Python code run faster in a function is because,  when a function is compiled, the local variables are stored in a fixed-size array (not a dictionary) and variable names are assigned to indexes. This is possible because we can't dynamically add local variables to a function. While retrieving a local variable is literally a pointer lookup into the list and a refcount increase on the PyObject which is trivial.

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.2k users

Browse Categories

...