def test(pattern, path, count): print 'fnmatch(%s, %s) %d times...' % (path, pattern, count) start_compile = datetime.now() compiled = Compiled(DFA(NFA.fnmatch(pattern))) compiled.optimize() # slow! end_compile = datetime.now() start_execution = datetime.now() for x in range(count): compiled(path) end_execution = datetime.now() native_test = compile_native_test(compiled, pattern, path, count) start_native = datetime.now() native_test() end_native = datetime.now() from fnmatch import fnmatch start_builtin = datetime.now() for x in range(count): fnmatch(path, pattern) end_builtin = datetime.now() return { 'pattern': pattern, 'path': path, 'count': count, 'compile_time': (end_compile-start_compile), 'execution_time': (end_execution-start_execution), 'native_time': (end_native-start_native), 'builtin_time': (end_builtin-start_builtin), }
#!/usr/bin/env python # our code from dfa import DFA from nfa import NFA from compiler import Compiled # the python implementation import fnmatch # run unit self tests from characterset import test_CharacterSet test_CharacterSet() from dfa import test_distinctArcs test_distinctArcs() PATTERNS = ('*.txt', '*', '*.*', 'README.*') PATHS = ('test.c', 'README.txt', 'README') for pattern in PATTERNS: nfa = NFA.fnmatch(pattern) dfa = DFA(nfa) compiled = Compiled(dfa, debug=False) compiled.optimize() for path in PATHS: expected = fnmatch.fnmatch(path, pattern) assert nfa(path) == expected assert dfa(path) == expected assert compiled(path) == expected
if __name__ == '__main__': from optparse import OptionParser op = OptionParser(usage='usage: %prog [options] pattern') op.add_option('--dont-optimize', dest='optimize', help='optimize the generated code', action='store_false', default=True) op.add_option('--native', dest='native', help='generate native assembly rather than LLVM assembly', action='store_true', default=False) (options, args) = op.parse_args() if len(args) != 1: op.print_help() else: from nfa import NFA from dfa import DFA dfa = DFA(NFA.fnmatch(args[0])) compiled = Compiled(dfa) if options.optimize: compiled.optimize() if options.native: from subprocess import Popen, PIPE asm = Popen('llvm-as | llc', shell=True, stdin=PIPE, stdout=PIPE) asm.stdin.write(str(compiled)) asm.stdin.close() print asm.stdout.read() else: print compiled