Skip to content

Instantly share code, notes, and snippets.

@leetrout
Forked from kipanshi/gist:4007717
Last active December 11, 2015 00:19
Show Gist options
  • Save leetrout/4515970 to your computer and use it in GitHub Desktop.
Save leetrout/4515970 to your computer and use it in GitHub Desktop.
import cProfile
from django.template.defaultfilters import floatformat as floatformat_django
from django.contrib.humanize.templatetags.humanize import intcomma as intcomma_django
num = 100000
float_num = 1 / 3.0
def floatformat(value, places=2):
"""Display only desired number of deciaml places. Returns string."""
left, right = str(value).split('.')
return '.'.join((left, right[:places]))
def intcomma(value):
"""Add comma on every 10^3. Returns string."""
value = str(value)
is_negative = False
if value.startswith('-'):
is_negative = True
value = value[1:]
dot_position = value.find('.')
if dot_position != -1:
int_part, decimal_part = value[:dot_position], value[dot_position:]
else:
int_part, decimal_part = value, ''
comma_position = int_part.find(',')
if comma_position != -1:
left, right = int_part[:comma_position], int_part[comma_position:]
else:
left, right = int_part, ''
if len(left) > 3:
comma_ready = ''.join((intcomma(left[:-3]), ',', left[-3:], right))
if decimal_part:
return ''.join((comma_ready, decimal_part))
else:
return comma_ready
if is_negative:
value = '-' + value
return value
#===================
# PROFILING RESULTS
#===================
# >>> cProfile.run('for i in xrange(4000): intcomma_django(num)')
# 124002 function calls (120002 primitive calls) in 0.209 seconds
# ^^^^^^ ^^^^^
#
# >>> cProfile.run('for i in xrange(4000): intcomma(num)')
# 36002 function calls (32002 primitive calls) in 0.031 seconds
#
# >>> cProfile.run('for i in xrange(4000): floatformat_django(float_num, 3)')
# 1076002 function calls (1064002 primitive calls) in 1.446 seconds
# ^^^^^^^ ^^^^^ !!!
#
# >>> cProfile.run('for i in xrange(4000): floatformat(float_num, 3)')
# 12002 function calls in 0.022 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment