Created
September 2, 2012 14:47
-
-
Save starenka/3599827 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import izip_longest | |
def intseparator(value, separator=" ", group_every=3): | |
if '.' in value or ',' in value: | |
return value | |
def grouper(n, iterable, padvalue=None): | |
return izip_longest(*[iter(iterable)] * n, fillvalue=padvalue) | |
return separator.join(map(''.join, grouper(group_every, reversed(value), '')))[::-1] | |
import re | |
def intseparator_old(value, separator=" "): | |
new = re.sub("^(-?\d+)(\d{3})", '\g<1>' + separator + '\g<2>', value) | |
if value == new: | |
return new | |
else: | |
return intseparator_old(new, separator) | |
from timeit import Timer | |
from random import randint | |
from functools import partial | |
vals = ['123', '123.32', '160,23'] + [str(randint(1, 9) * (10 ** randint(1, 9))) for one in range(20)] | |
for i, one in enumerate(vals): | |
print '===', one | |
print 'new', Timer(partial(intseparator, one)).timeit(number=10000) | |
print 'old', Timer(partial(intseparator_old, one)).timeit(number=10000) | |
''' | |
=== 123 | |
new 0.0551390647888 | |
old 0.0619730949402 | |
=== 123.32 | |
new 0.00204801559448 | |
old 0.0639929771423 | |
=== 160,23 | |
new 0.00232195854187 | |
old 0.0642800331116 | |
=== 400000000 | |
new 0.040027141571 | |
old 0.250786781311 | |
=== 2000000 | |
new 0.0401909351349 | |
old 0.24866104126 | |
=== 2000 | |
new 0.0389459133148 | |
old 0.151959896088 | |
=== 40000 | |
new 0.0383281707764 | |
old 0.15451002121 | |
=== 6000000 | |
new 0.0401420593262 | |
old 0.247751951218 | |
=== 5000 | |
new 0.0387279987335 | |
old 0.153437852859 | |
=== 200 | |
new 0.0362091064453 | |
old 0.0630459785461 | |
=== 20000 | |
new 0.0388009548187 | |
old 0.154855966568 | |
=== 400 | |
new 0.0361289978027 | |
old 0.0620431900024 | |
=== 700000000 | |
new 0.0403130054474 | |
old 0.253783941269 | |
=== 800000 | |
new 0.0393478870392 | |
old 0.154774904251 | |
=== 90000 | |
new 0.0382339954376 | |
old 0.154028177261 | |
=== 400 | |
new 0.0360498428345 | |
old 0.059700012207 | |
=== 800000 | |
new 0.0389120578766 | |
old 0.154366970062 | |
=== 200 | |
new 0.0356450080872 | |
old 0.0606961250305 | |
=== 10000 | |
new 0.0382850170135 | |
old 0.15410399437 | |
=== 600000 | |
new 0.0388000011444 | |
old 0.155707836151 | |
=== 100000000 | |
new 0.0406899452209 | |
old 0.250066995621 | |
=== 50000 | |
new 0.0386528968811 | |
old 0.154365062714 | |
=== 300 | |
new 0.0361127853394 | |
old 0.0604050159454 | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment