Skip to content

Instantly share code, notes, and snippets.

@python1981
Forked from kipanshi/gist:4007717
Created September 2, 2020 16:26
Show Gist options
  • Save python1981/ffeb3725b977b6c36f5c8e038c7e8f35 to your computer and use it in GitHub Desktop.
Save python1981/ffeb3725b977b6c36f5c8e038c7e8f35 to your computer and use it in GitHub Desktop.
Django float format and intcomma optimization
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)
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
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