Skip to content

Instantly share code, notes, and snippets.

@jeethu
Created March 27, 2012 12:18
Show Gist options
  • Save jeethu/2215423 to your computer and use it in GitHub Desktop.
Save jeethu/2215423 to your computer and use it in GitHub Desktop.
A slightly faster way to decode ints and floats?
import os
import random
import re
import time
l = []
for x in range(100000):
l.append(random.choice(
[None, str(random.randint(-10000, 10000)),
str(random.random()),
os.urandom(100)]))
INT_RE = re.compile(r'^[-+]?\d+$')
FLOAT_RE = re.compile(r'^[-+]?[0-9]*.[0-9]+(e[-+]\d+)?$')
def decode_re(messages):
l = []
for x in messages:
if x is None:
r = x
elif INT_RE.match(x):
r = int(x)
elif FLOAT_RE.match(x):
r = float(x)
else:
r = x
l.append(r)
return l
def decode_old(messages):
l = []
for x in messages:
if x is None:
r = x
else:
try:
r = int(x) if x.find('.') == -1 else float(x)
except ValueError:
r = x
l.append(r)
return l
def main():
re_time = 0
int_time = 0
N = 10
for x in range(N):
t = time.clock()
l1 = decode_old(l)
int_time += (time.clock() - t)
t = time.clock()
l2 = decode_re(l)
re_time += (time.clock() - t)
if l1 != l2:
for a, b in zip(l1, l2):
if a != b:
t = (a, type(a), b, type(b))
print '\"%s\" (%s)(old) != \"%s\" (%s)(re)' % t
print 'Error: results don\'t match'
break
re_time /= N
int_time /= N
print 'old fn time: %f' % int_time
print 'new fn time: %f' % re_time
fn_name = 'old' if int_time < re_time else 'new'
faster = 1.0 - (int_time / re_time if int_time < re_time
else re_time / int_time)
t = (fn_name, faster * 100, abs(re_time - int_time))
print '%s is %f%% faster (%f seconds delta)' % t
print 'average of %d iterations' % (N,)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment