Sep 18, 2019

python timeit re vs compiled re

import re
import timeit

s = 'strings are strings'
compiled_regex = re.compile(r'(str)in(gs)')

def not_compiled_func():
   r = re.match(r'(str)in(gs)', s) 
   #print(r.group())

def compiled_func():
  r = compiled_regex.match(s)
  #print(r.group()) 

t1 = timeit.timeit(stmt=not_compiled_func, number=1000000)
print('%0.2f' % t1)  #5.65 secs
t2 = timeit.timeit(stmt=compiled_func, number=1000000)
print('%0.2f' % t2)  #1.73 secs



No comments:

Post a Comment