Skip to content

Instantly share code, notes, and snippets.

@sarum90
Last active March 30, 2016 15:58
Show Gist options
  • Save sarum90/00d837d89f9a99c5ac7a9e09a713eb1b to your computer and use it in GitHub Desktop.
Save sarum90/00d837d89f9a99c5ac7a9e09a713eb1b to your computer and use it in GitHub Desktop.
import timeit
_ATOMIC_TYPES_LIST = [bool, int, float, str, unicode]
_ATOMIC_TYPES_SET = set(_ATOMIC_TYPES_LIST)
def is_a_type(x):
t = type(x)
if (t is bool or
t is int or
t is float or
t is str or
t is unicode):
return x
return 'UNK'
def is_a_type_l(x):
t = type(x)
if t in _ATOMIC_TYPES_LIST:
return x
return 'UNK'
def is_a_type_s(x):
t = type(x)
if t in _ATOMIC_TYPES_SET:
return x
return 'UNK'
def is_an_instance(x):
if isinstance(x, (bool, int, float, str, unicode)):
return x
return 'UNK'
def run(f):
return [f(x) for x in (True, 1, 3.2, "dog", u"cat", {})]
for x in xrange(2):
print "is a type: "
print timeit.timeit(lambda: run(is_a_type))
print ""
print "is a type (list): "
print timeit.timeit(lambda: run(is_a_type_l))
print ""
print "is a type (set): "
print timeit.timeit(lambda: run(is_a_type_s))
print ""
print "is an instance: "
print timeit.timeit(lambda: run(is_an_instance))
print ""
# Output
#
# is a type:
# 2.10327100754
#
# is a type (list):
# 1.94879198074
#
# is a type (set):
# 1.77079796791
#
# is an instance:
# 3.94516301155
#
# is a type:
# 2.12281799316
#
# is a type (list):
# 1.96864295006
#
# is a type (set):
# 1.74609208107
#
# is an instance:
# 3.95978212357
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment