Last active
February 13, 2017 16:35
-
-
Save binki/2a484f6bf8da044f6d482db5e2a98a14 to your computer and use it in GitHub Desktop.
if is faster than try?
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/env python3 | |
from os.path import dirname, realpath | |
import sys | |
from timeit import Timer | |
sys.path.append(dirname(realpath(__file__))) | |
def ifway3(b): | |
a=1 | |
if not b == 0: | |
ret = a/b | |
def ifway3_0(): | |
ifway3(0) | |
def ifway3_1(): | |
ifway3(1) | |
def tryway3(b): | |
a=1 | |
try: | |
ret=a/b | |
except: | |
pass | |
def tryway3_0(): | |
tryway3(0) | |
def tryway3_1(): | |
tryway3(1); | |
def dorun(callable): | |
number, total_elapsed = Timer(callable).autorange() | |
return total_elapsed/number | |
if __name__ == '__main__': | |
for warmup in [True, False]: | |
for method in [('ifway3_0', ifway3_0, ), ('tryway3_0', tryway3_0, ), ('ifway3_1', ifway3_1, ), ('tryway3_1', tryway3_1, ), ]: | |
# Docs from Timer suggest that shortest time is most | |
# likely to be closest to the limit. Variance (longer | |
# times) is likely due to OS stealing timeslices and other | |
# factors. So grab three samples per thing. | |
elapsed = min(dorun(method[1]) for x in range(0, 3)) | |
if not warmup: | |
print(','.join(str(x) for x in [method[0], elapsed])) |
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
$ python py_except_speed.py | |
ifway3_0,2.295694221095319e-07 | |
tryway3_0,4.635965666751378e-07 | |
ifway3_1,2.6982194153560267e-07 | |
tryway3_1,2.3311285575462116e-07 | |
$ uname -a | |
MSYS_NT-10.0 DESKTOP-A4G2C0J 2.6.0(0.304/5/3) 2016-09-07 20:45 x86_64 Msys | |
$ python -VV | |
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment