Skip to content

Instantly share code, notes, and snippets.

@JoaoGFarias
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoaoGFarias/9024978 to your computer and use it in GitHub Desktop.
Save JoaoGFarias/9024978 to your computer and use it in GitHub Desktop.
'''
Look at foo1 and foo2
Foo1 makes a comparison, uses an if on each interation and is able to stop interacting at any point of the array
Foo2 a comparison, a boolean calculus and an attribution at each interaction, and always loop through ALL the array
Let's see how they run...
'''
import time
from random import randrange
def timeSpent(foo,data):
start = time.time()
foo(data)
print(time.time() - start)
def foo1(data):
for elem in data:
if elem == 2:
return False
return True
def foo2(data):
x = True
for elem in data:
x = x and elem == 2
return x
dataSize = 10000000
data = [0 for x in range(0,dataSize)]
print("All array:")
timeSpent(foo1,data)
timeSpent(foo2,data)
print("Stop Flag in any point array:")
randPoint = randrange(dataSize)
data[randPoint] = 2
timeSpent(foo1,data)
timeSpent(foo2,data)
data[randPoint] = 0
print("Stop Flag at the beginning:")
data[int(randrange(dataSize)/8)] = 2
timeSpent(foo1,data)
timeSpent(foo2,data)
'''
Some results:
All array:
0.44402503967285156
0.2850170135498047
Stop Flag in any point array:
0.3480198383331299
0.2830159664154053
Stop Flag at the beginning:
0.04200291633605957
0.29201602935791016
------------
All array:
0.443026065826416
0.29401707649230957
Stop Flag in any point array:
0.25101399421691895
0.28401684761047363
Stop Flag at the beginning:
0.03500199317932129
0.28401613235473633
-----------------------
All array:
0.4450259208679199
0.2830159664154053
Stop Flag in any point array:
0.10200619697570801
0.2830159664154053
Stop Flag at the beginning:
0.043003082275390625
0.2960169315338135
----------------------------
Therefore, the if on line 10 made foo1 much slower when looping through all the array
Foo1 is worth only when there is certainty that it will stop at the beginning of the array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment