Skip to content

Instantly share code, notes, and snippets.

@robertwb
Last active January 4, 2017 07:55
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 robertwb/0ef6bfaa3c9b2ea11ed64d1c1a0bda43 to your computer and use it in GitHub Desktop.
Save robertwb/0ef6bfaa3c9b2ea11ed64d1c1a0bda43 to your computer and use it in GitHub Desktop.
# Drop this in the Demos directory of Cython and run
# python setup.py build_ext --inplace && python -c 'import time_exc'
# cython: cdivision=True
# distutils: extra_compile_args = -O3
import time
cdef int with_nothing(bint bad):
if bad:
try:
raise ValueError()
except:
pass
cdef int with_star(bint bad) except *:
if bad:
raise ValueError()
cdef int with_value(bint bad) except -0xBadBad:
if bad:
raise ValueError()
cdef int with_maybe_value(bint bad) except? -0xBadBad:
if bad:
raise ValueError()
def time_with_nothing(long N, bint any_bad):
cdef int k
if any_bad:
for k in range(N):
try:
with_nothing(k % 2)
except:
pass
else:
for k in range(N):
with_nothing(False)
def time_with_star(long N, bint any_bad):
cdef int k
if any_bad:
for k in range(N):
try:
with_star(k % 2)
except:
pass
else:
for k in range(N):
with_star(False)
def time_with_value(long N, bint any_bad):
cdef int k
if any_bad:
for k in range(N):
try:
with_value(k % 2)
except:
pass
else:
for k in range(N):
with_value(False)
def time_with_maybe_value(long N, bint any_bad):
cdef int k
if any_bad:
for k in range(N):
try:
with_maybe_value(k % 2)
except:
pass
else:
for k in range(N):
with_maybe_value(False)
#TODO: Use timeit
def time_all(base, any_bad):
fs = [time_with_nothing, time_with_star, time_with_value, time_with_maybe_value]
for ix, f in enumerate(fs * 4):
if ix % len(fs) == 0:
print
t = time.time()
N = base * (ix // len(fs) + 1)
f(N, any_bad)
elapsed = time.time() - t
print f.__name__, ' \t', elapsed, ' \t', elapsed / N
time_all(1000000, True)
print
time_all(100000000, False)
print
print "DONE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment