1#-*- coding: utf-8 -*-
2#######################################################################
3# Testing parsing speed. This is used for the purpose of testing
4#   of performance gains/loses for various approaches.
5# Author: Igor R. Dejanovic <igor DOT dejanovic AT gmail DOT com>
6# Copyright: (c) 2016 Igor R. Dejanovic <igor DOT dejanovic AT gmail DOT com>
7# License: MIT License
8#######################################################################
9from __future__ import print_function, unicode_literals
10
11import codecs
12import time
13from os.path import dirname, join, getsize
14from arpeggio import ParserPython
15from grammar import rhapsody
16
17def timeit(parser, file_name, message):
18    print(message, 'File:', file_name)
19    file_name = join(dirname(__file__), 'test_inputs', file_name)
20    file_size = getsize(file_name)
21    print('File size: {:.2f}'.format(file_size/1000), 'KB')
22
23    with codecs.open(file_name, "r", encoding="utf-8") as f:
24        content = f.read()
25
26    t_start = time.time()
27    parser.parse(content)
28    t_end = time.time()
29
30    print('Elapsed time: {:.2f}'.format(t_end - t_start), 'sec')
31    print('Speed = {:.2f}'.format(file_size/1000/(t_end - t_start)), 'KB/sec')
32
33    if parser.memoization:
34        print('Cache hits = ', parser.cache_hits)
35        print('Cache misses = ', parser.cache_misses)
36        print('Success ratio[%] = ',
37              parser.cache_hits*100/(parser.cache_hits + parser.cache_misses))
38    print()
39
40
41def main():
42
43    # Small file
44    file_name_small = 'LightSwitch.rpy'
45    # Large file
46    file_name_large = 'LightSwitchDouble.rpy'
47
48    # No memoization
49    parser = ParserPython(rhapsody)
50    print('\n*** No memoization\n')
51    for i in range(3):
52        timeit(parser, file_name_small,
53               '{}. Small file, no memoization.'.format(i + 1))
54        timeit(parser, file_name_large,
55               '{}. Large file, no memoization.'.format(i + 1))
56
57    # Memoization
58    parser = ParserPython(rhapsody, memoization=True)
59    print('\n*** Memoization\n')
60    for i in range(3):
61        timeit(parser, file_name_small,
62               '{}. Small file, with memoization.'.format(i + 1))
63        timeit(parser, file_name_large,
64               '{}. Large file, with memoization.'.format(i + 1))
65
66if __name__ == '__main__':
67    main()
68