Skip to content

Instantly share code, notes, and snippets.

@BoboTiG
Created December 19, 2017 20:51
Show Gist options
  • Save BoboTiG/c0826bceac71763d16a95a4ee3e083c2 to your computer and use it in GitHub Desktop.
Save BoboTiG/c0826bceac71763d16a95a4ee3e083c2 to your computer and use it in GitHub Desktop.
Simple and naive benchmark for the PR
from timeit import Timer
setup = """
def func_orig(value):
return True if len(value) > 0 else False
def func_new(value):
return value != ''
"""
print('isnonempty()')
print(' original:', min(Timer("func_orig('a')", setup=setup).repeat(1000, 9000)))
print(' proposal:', min(Timer("func_new('a')", setup=setup).repeat(1000, 9000)))
# 0.000838826992549002
# 0.000603156047873199
setup = """
import re
def func_orig(value):
hexa_decimal = re.compile(r"^[0-9a-fA-F]+$")
return bool(hexa_decimal.match(value))
def func_new(value):
try:
return int(value, 16) >= 0
except ValueError:
return False
"""
print('ishexadecimal()')
print(' original:', min(Timer("func_orig('a' * 12345678)", setup=setup).repeat(10, 10)))
print(' proposal:', min(Timer("func_new('a' * 12345678)", setup=setup).repeat(10, 10)))
# 2.9302719940897077
# 1.435651743086055
setup = """
import re
def func_orig(value):
pattern = re.compile(r"^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
return bool(pattern.match(value))
def func_new(value):
value = value.lstrip('#')
try:
return int(value, 16) >= 0 and len(value) in (3, 6)
except ValueError:
return False
"""
print('ishexcolor()')
print(' original:', min(Timer("func_orig('aBcD09')", setup=setup).repeat(1000, 900)))
print(' proposal:', min(Timer("func_new('aBcD09')", setup=setup).repeat(1000, 900)))
# 0.007065132958814502
# 0.003196523990482092
setup = """
import re
def ishexadecimal(value):
try:
return int(value, 16) >= 0
except ValueError:
return False
def func_orig(value):
integer = re.compile(r"^(?:[-+]?(?:0|[1-9][0-9]*))$")
return value != '' and bool(integer.match(value))
def func_new(value):
return ishexadecimal(value) and len(value) == 32
"""
print('ismd5()')
print(' original:', min(Timer("func_orig('d94f3f016ae679c3008de268209132f2')", setup=setup).repeat(1000, 900)))
print(' proposal:', min(Timer("func_new('d94f3f016ae679c3008de268209132f2')", setup=setup).repeat(1000, 900)))
# 0.006366040906868875
# 0.0031074760481715202
setup = """
def func_orig(value):
try:
port = int(value)
except ValueError:
return False
if 0 < port < 65536:
return True
else:
return False
def func_new(value):
try:
return 0 < int(value) < 65536
except ValueError:
return False
"""
print('isport()')
print(' original:', min(Timer("func_orig('8080')", setup=setup).repeat(1000, 900)))
print(' proposal:', min(Timer("func_new('8080')", setup=setup).repeat(1000, 900)))
# 0.0020653540268540382
# 0.0019679079996421933
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment