Skip to content

Instantly share code, notes, and snippets.

@melpomene
Created January 28, 2014 11:04
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 melpomene/8665726 to your computer and use it in GitHub Desktop.
Save melpomene/8665726 to your computer and use it in GitHub Desktop.
Compare isinstance, type and ducktyping to see which one is quickest.
import time
""""
Compare isinstance, type and ducktyping to see which one is quickest.
Typical output
=============
IsInstance 0.00567038607597
ducktyping 0.0232819545269
type 0.004327688694
""""
def first(i):
return isinstance(i, float)
def second(i):
try:
i.is_integer()
return True
except:
return False
def third(i):
return type(i)== float
tot1=0
tot2=0
tot3=0
loops = 1000
for j in xrange(loops):
t = time.time()
a = map(lambda i: first(i), xrange(10000))
tot1 += time.time() -t
t = time.time()
a = map(lambda i: second(i), xrange(10000))
tot2 += time.time() -t
t = time.time()
a = map(lambda i: third(i), xrange(10000))
tot3 += time.time() -t
print "IsInstance", tot1 / float(loops)
print "ducktyping", tot2 / float(loops)
print "type", tot3 / float(loops)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment