Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import random
import timeit
number = 100000000
variations = 300
test_vals = tuple(tuple(random.randint(4, 10) for _x in range(6)) for i in range(variations))
t = timeit.timeit(
'num_good = 0\nfor (x,y,z,a,b,c) in test_vals:\n\tif 7 in (x,y,z,a,b,c):\n\t\tnum_good += 1',
globals={'test_vals': (vars_tuple for vars_tuple in test_vals)}, number=number
)
print(f'7 in (x,y,z,a,b,c): {t:.3g}')
t = timeit.timeit(
'num_good = 0\nfor (x,y,z,a,b,c) in test_vals:\n\tif 7 in {x,y,z,a,b,c}:\n\t\tnum_good += 1',
globals={'test_vals': (vars_tuple for vars_tuple in test_vals)}, number=number
)
print(f'7 in {{x,y,z,a,b,c}}: {t:.3g}')
t = timeit.timeit(
'num_good = 0\nfor (x,y,z,a,b,c) in test_vals:\n\tif any(_v == 7 for _v in (x,y,z,a,b,c)):\n\t\tnum_good += 1',
globals={'test_vals': (vars_tuple for vars_tuple in test_vals)}, number=number
)
print(f'any(_v == 7 for _v in (x,y,z,a,b,c)): {t:.3g}')
t = timeit.timeit(
'num_good = 0\nfor (x,y,z,a,b,c) in test_vals:\n\tif x==7 or y==7 or z==7 or a==7 or b==7 or c==7:\n\t\tnum_good += 1',
globals={'test_vals': (vars_tuple for vars_tuple in test_vals)}, number=number
)
print(f'... = 7 or ... = 7 ...: {t:.3g}')
# 7 in (x,y,z,a,b,c): 4.18
# 7 in {x,y,z,a,b,c}: 4.19
# any(_v == 7 for _v in (x,y,z,a,b,c)): 4.22
# x == 7 or y == 7 or ...: 4.22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.