import timeit
import __main__
import random
import string
import re

N = 10 #Number of executions
L = 1000000 #Length of string
sym_rel_pos = 2

def test_f_re():
    pat = ''.join(random.sample(string.ascii_letters,3)) #prevent re caching
    s = '0'*(L - sym_rel_pos) + pat + '0'*sym_rel_pos
    return re.sub(r'(.*)'+pat,r'\1XXX',s)

compiled = re.compile(r'(.*)'+'jjj')
def test_f_re_with_caching():
    pat = ''.join(random.sample(string.ascii_letters,3)) #left here to produce comparable results with other functions
    s = '0'*(L - sym_rel_pos) + 'jjj' + '0'*sym_rel_pos
    return compiled.sub(r'\1XXX',s)

def test_f_replace():
    pat = ''.join(random.sample(string.ascii_letters,3)) 
    s = '0'*(L - sym_rel_pos) + pat + '0'*sym_rel_pos
    return s[::-1].replace(pat[::-1], "XXX"[::-1], 1)[::-1]
 
names = dir(__main__)
for name in names:
    attr = getattr(__main__,name)
    if hasattr(attr,'__call__'):
        if name.startswith('test_f_'):
            init_name = name + '_init'
            if hasattr(__main__, init_name):
                init = getattr(__main__,init_name)
            else:
                init = 'from __main__ import {name}'.format(name=name, L=L)
            t = timeit.Timer(stmt='{name}()'.format(name=name),
                             setup=init)

            time = t.timeit(N)
            print('{name}: {time}'.format(name=name,time=time))