Evan Quiney
Evan Quiney

Reputation: 95

Do if statements take significant amounts of time in python?

I am creating a graphing program which has to iterate values through a calculation 10000-1000000 times, and then append part of that output to a list. In order to change which list it is appended to, there are ~3 if statements inside that loop. While it would logically be faster to use the if statement first, is there a significant amount of time saved?

As an example:

output = []
append_to = "pol"
for i in range(10000):
    if append_to == "pol":
        output.append(np.cos(i))
    else:
        output.append(np.sin(i))

Would this be significantly slower than:

output = []
append_to = "pol"
if append_to == "pol":
    for i in range(10000):
        output.append(np.cos(i))
else:
    for i in range(10000):
        output.append(np.sin(i))

Upvotes: 0

Views: 96

Answers (2)

Jose A. García
Jose A. García

Reputation: 888

Why dont just try?

import numpy as np
import timeit

def one():
    output = []
    append_to = "pol"
    for i in range(10000):
        if append_to == "pol":
            output.append(np.cos(i))
        else:
            output.append(np.sin(i))

def two():
    output = []
    append_to = "pol"
    if append_to == "pol":
        for i in range(10000):
            output.append(np.cos(i))
    else:
        for i in range(10000):
            output.append(np.sin(i))

print(timeit.timeit('f()', 'from __main__ import one as f', number=1000))
print(timeit.timeit('f()', 'from __main__ import two as f', number=1000))

Output:
9.042721510999854
8.626055914000062

So yes, it is faster, as expected. And just for you to know the lookup also takes a bit of time, so if you do ap = output.append and then call ap instead of output.append you get a marginal improvement.

Upvotes: 2

Polymer
Polymer

Reputation: 1108

Give it a try!

import math, time

time_start = time.time()

output = []
append_to = "pol"
for i in range(10000000):
    if append_to == "pol":
        output.append(math.cos(i))
    else:
        output.append(math.sin(i))

print("End: " + str(time.time() - time_start))

For that run, I got 4.278s. For this run:

import math, time

time_start = time.time()

output = []
append_to = "pol"
if append_to == "pol":
    for i in range(10000000):
        output.append(math.cos(i))
else:
    for i in range(10000000):
        output.append(math.sin(i))

print("End: " + str(time.time() - time_start))

I got 3.751s.

So there you go!

Upvotes: 2

Related Questions