Benchmarking Local and Global Variables, and List Comprehension in Python

Published on January 03, 2024

This article compares the program execution speed while using local and global variables in Python. Are local variables faster than global variables? We also added an example of list comprehension to this benchmarking article.

Benchmarks between local, global and list comprehension in Python

What is a global variable?

A global variable can be used anywhere in the program. It is created outside a function. It can be used anywhere, in any function and outside functions.

In this example, variable fruit is a global variable.

fruit = 'banana'

def foo():
    print('The fruit is', fruit)

foo()

OUTPUT:

The fruit is banana

You can also create a global variable from inside a function. This is done by using the global keyword.

def foo():
    global fruit
    fruit = 'banana'

foo()
print('The fruit is', fruit)

OUTPUT:

The fruit is banana

What is a local variable?

A local variable is a variable created inside a function. The life of this variable ends when the control exits the function. The local variable cannot be accessed from outside the function.

In this case, let us create a local variable fruit and try to access it from outside the functio. We get a not defined error.

def foo():
    fruit = 'banana'

foo()
print('The fruit is', fruit)

OUTPUT:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'fruit' is not defined. Did you mean: 'quit'?

Let us call fruit from within the function that defined it.

def foo():
    fruit = 'banana'
    print('The local fruit is', fruit)

foo()

OUTPUT:

The local fruit is banana

Variable scope and LEGB rule

A variable scope refers to the region in the code where we can access a variable.

The acronym LEGB stand for Local, Enclosing, Global, and Built-in. When you use a variable, Python searches through these different scope levels. The preference is for the first occurrence.

Local scope is the region within the function. This scope contains the variables defined inside the function. These variables are only accessible from the code within the function. Variables created here are created at function call and not at function definition. So, if you call the same function multiple times, a separate local scope is created each time.

Enclosing scope is a scope for nested functions. The enclosing scope is the scope of the outer or enclosed function and contains the variables defined in the enclosing function. The variables defined in this scope are visible from the inner and enclosing functions.

Global scope is the highest level scope in a Python program. Variables in this scope are accessible anywhere in the code throughout the program.

Built-in scope is created when a program is run. This scope contains functions, keywords, exceptions, and functions. Variables in this scope are accessible anywhere in the code. This scope is automatically loaded by Python when the program is executed.

What is list comprehension?

A list comprehension is an efficient substitute for the for loop. It is faster because there is no need to load the append attribute of the list and call it as a function at each iteration. This way, list comprehensions do not have to suspend and resume a function or multiple functions' frames. This way, using list comprehensions is much faster than regular for loop iterations.

Our benchmarking problem

We will write a Python program to create a list with all the even numbers from 1 through 5 million. This program will have an if condition to check for even or odd.

Program using list as a global variable

We will first create a program that uses only global variables. Let us call this program even_global.py

even_numbers = []
for i in range(5000000):
    if i % 2 == 0:
        even_numbers.append(i)

Now, import the time module and call time.perf_counter() to measure the elapsed time.

This is the complete program.

import time

start_time = time.perf_counter()

even_numbers = []
for i in range(5000000):
    if i % 2 == 0:
        even_numbers.append(i)

end_time = time.perf_counter()
print(f'Total Time: {round(end_time - start_time, 5)} seconds')

When we run this program, the output can be similar to this:

$ python even_global.py
Total Time: 0.57201

Program using list as a local variable

We will create a new Python program called even_local.py

Now, create a function get_even_numbers() which returns a list of even numbers from 1 through 5 million. Add the time.perf_counter() code in the main function.

import time

def get_even_numbers():
    even_numbers = []
    for i in range(5000000):
        if i % 2 == 0:
            even_numbers.append(i)
    return even_numbers

start_time = time.perf_counter()
prime_numbers = get_even_numbers()

end_time = time.perf_counter()
print(f'Total Time: {round(end_time - start_time, 5)} seconds')

When we run this program, the output will be similar to this:

$ python even_local.py 
Total Time: 0.29298 seconds

The run time is much lower, almost half. You can run it several times, just to make sure.

Program using List Comprehension

We will create a new program called even_list_comprehension.py

This will be our code to create the list of even numbers.

import time

start_time = time.perf_counter()

even_numbers = [i for i in range(5000000) if i % 2 == 0]

end_time = time.perf_counter()
print(f'Total Time: {round(end_time - start_time, 5)} seconds')

When we run this program, the output will be similar to this:

$ python even_list_comprehension.py 
Total Time: 0.26939 seconds

Complete benchmarking code

This is the complete benchmarking code for each of the three programs.

1) even_global.py

import time

start_time = time.perf_counter()

even_numbers = []
for i in range(5000000):
    if i % 2 == 0:
        even_numbers.append(i)

end_time = time.perf_counter()
print(f'Total Time: {round(end_time - start_time, 5)} seconds')

2) even_local.py

import time

def get_even_numbers():
    even_numbers = []
    for i in range(5000000):
        if i % 2 == 0:
            even_numbers.append(i)
    return even_numbers

start_time = time.perf_counter()
prime_numbers = get_even_numbers()

end_time = time.perf_counter()
print(f'Total Time: {round(end_time - start_time, 5)} seconds')

3) even_list_comprehension.py

import time

start_time = time.perf_counter()

even_numbers = [i for i in range(5000000) if i % 2 == 0]

end_time = time.perf_counter()
print(f'Total Time: {round(end_time - start_time, 5)} seconds')

And, the bar graph result:

Benchmarks between local, global and list comprehension in Python

Conclusion

If you have any particular use case that you would like to share, feel free to contact me or comment below.

Related Posts

If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom. You can also post questions in our Facebook group. Thank you.

Disclaimer: Our website is supported by our users. We sometimes earn affiliate links when you click through the affiliate links on our website.

Published on January 03, 2024

← Previous Post
Generate Random Data using Python

Next Post →
Apple AirTag Review