Last active
September 6, 2018 16:53
-
-
Save vchoi/d2604a524036668207a7b97bf48dd3c6 to your computer and use it in GitHub Desktop.
exception handling faster than if comparison?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
# | |
# Someone said that this is actually faster than using an if statement | |
# https://twitter.com/flibitijibibo/status/1037011978600898560 | |
# | |
# output: | |
# Running each function 100000000 times. | |
# isEqual_if(n=1.1,m=1.1), total 15.401655944995582, each 1.5401655944995582e-07. | |
# isEqual_if(n=1.1,m=0.1), total 15.192942995985504, each 1.5192942995985504e-07. | |
# isEqual_exception(n=1.1,m=1.1), total 41.77682093999465, each 4.177682093999465e-07. | |
# isEqual_exception(n=1.1,m=0.1), total 18.956408566999016, each 1.8956408566999015e-07. | |
# | |
# not in python... | |
from timeit import timeit | |
def isEqual_if(n, m): | |
if n == m: | |
return True | |
return False | |
def isEqual_exception(n, m): | |
try: | |
x = 1/(n-m) | |
except ZeroDivisionError: | |
return True | |
return False | |
def timeFuncs(functionList): | |
max = 1*10**8 | |
testValues = (1.1, 0.1) | |
print("Running each function {} times.".format(max)) | |
for function in functionList: | |
n = testValues[0] | |
for m in testValues: | |
def testfunc(): return function(n, m) | |
time = timeit(stmt=testfunc, number=max) | |
print("{}(n={},m={}), total {}, each {}.".format(function.__name__, | |
n, m, time, time/max)) | |
funclist = [isEqual_if, isEqual_exception] | |
timeFuncs(funclist) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment