Skip to content

Instantly share code, notes, and snippets.

@nelsnelson
Created April 25, 2014 18:45
Show Gist options
  • Save nelsnelson/11299259 to your computer and use it in GitHub Desktop.
Save nelsnelson/11299259 to your computer and use it in GitHub Desktop.
Conditional function invocations versus hashed function invocations
#! /usr/bin/env python
import sys
quiet = False
def noop0():
if not quiet:
sys.stdout.write('0')
def noop1():
if not quiet:
sys.stdout.write('1')
def noop2():
if not quiet:
sys.stdout.write('2')
def noop3():
if not quiet:
sys.stdout.write('3')
def noop4():
if not quiet:
sys.stdout.write('4')
def noop5():
if not quiet:
sys.stdout.write('5')
def noop6():
if not quiet:
sys.stdout.write('6')
def noop7():
if not quiet:
sys.stdout.write('7')
def noop8():
if not quiet:
sys.stdout.write('8')
def noop9():
if not quiet:
sys.stdout.write('9')
def run_conditional_test(n):
print "Running conditional test..."
for x in range(0, n):
x = x % 10
if x == 0:
noop0()
elif x == 1:
noop1()
elif x == 2:
noop2()
elif x == 3:
noop3()
elif x == 4:
noop4()
elif x == 5:
noop5()
elif x == 6:
noop6()
elif x == 7:
noop7()
elif x == 8:
noop8()
elif x == 9:
noop9()
print ''
FUNC_MAP = {
0: noop0,
1: noop1,
2: noop2,
3: noop3,
4: noop4,
5: noop5,
6: noop6,
7: noop7,
8: noop8,
9: noop9
}
def run_hash_test(n):
print "Running hash test..."
for x in range(0, n):
x = x % 10
FUNC_MAP[x]()
print ''
if __name__ == '__main__':
n = int(sys.argv[1])
if len(sys.argv) > 2:
mode = sys.argv[2]
else:
mode = 'conditional'
if n > 10000:
quiet = True
if mode == 'hash':
run_hash_test(n)
else:
run_conditional_test(n)
$ time (./hashcomp.py 100000000)
Running conditional test...
real 0m42.223s
user 0m38.594s
sys 0m1.994s
$ time (./hashcomp.py 100000000 hash)
Running hash test...
real 0m30.787s
user 0m29.228s
sys 0m1.534s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment