The Need for Speed: Does fewer operators improve speed in Python?


Introduction

As developers, we are always on the lookout for ways to optimize our code and make it run faster. One intriguing question that often arises is whether using fewer operators in conditional statements can actually impact the speed of Python code. In this blog post, we'll explore the nuances of Python conditionals and investigate whether simplicity in operators correlates with improved performance.

The Test

The goal of this experiment is to speed up python code by using fewer operators. To achieve this, we aim to create equivalent sets of conditions with varying numbers of operators, delving into the realm of Discrete Mathematics for a strategic approach. Leveraging De Morgan's Theorem, we can rewrite two conditional statements into equivalent yet structurally distinct forms. This operation allows us to realistically test the result of employing fewer operators and their potential influence on overall code efficiency.

De Morgan's Theorem is a set of rules in Boolean Algebra that provides transformations for logical expressions. It describes how to negate complex logical statements involving both AND and OR operations. In simpler terms, it allows us to express the negation of a compound statement by negating its individual parts and switching the logical AND to OR (or vice versa).

For example:

  • Original Expression: not (A and B)
  • Applying De Morgan's Theorem: (not A) or (not B)

It seems likely that using fewer operators would make a significant impact on the runtime of our code. Lets write a script to test that.

The Code

                        
#python3
"""
Python if logic speed testing:
Test if an 'if' will process
faster if it uses fewer 'gates'
"""

import time, random

print("Processing long condition...")
start = time.time()
for i in range(0,1000):
    # get 2 random real numbers btwn 0 and 1
    a = random.random()
    b = random.random()

    if not (a >= 0.5) or not(b >= 0.5):
        pass

longConditionTime = time.time() - start

print("Processing short condition...")
start = time.time()
for i in range(0,1000):
    # get 2 random real numbers btwn 0 and 1
    a = random.random()
    b = random.random()

    if not (a >= 0.5 and b >= 0.5):
        pass

shortConditionTime = time.time() - start

print("Results:")
print("Long Condition Time:\t%f" %longConditionTime)
print("Short Condition Time:\t%f" %shortConditionTime)
print("Difference:\t\t%f" %(longConditionTime-shortConditionTime))

                        
                    

The Results

This code compares the execution time of two similar loops that generate random real numbers between 0 and 1. The first loop has a longer condition involving two or operators, while the second loop has a shorter condition using and. The code measures the time it takes to process each loop and prints the results, providing insights into whether the length and structure of conditional statements impact the overall execution speed. The output includes the time taken for both the long and short conditions, as well as the difference in processing time between the two.

Number of Iterations 3 Operator Conditional (sec) 2 Operator Conditional (sec) Time Delta (sec)
1000 0.001003 0.000985 0.000018
1000000 0.250852 0.232852 0.018
1000000000 222.685095 222.001522 0.683573

Conclusion

In the conducted experiments with varying numbers of iterations, the results consistently show that the short condition, utilizing the and operator, tends to have a slightly faster execution time compared to the long condition with or operators. The difference in processing time increases marginally with a higher number of iterations, suggesting that the structure of conditional statements may have a subtle impact on performance, becoming more noticeable with larger datasets.

If you are a developer looking to get a slight margin of performance improvement on your next project, using Discrete Mathematics to optimize your code could make a world of difference.