source: doc/theses/andrew_beach_MMath/code/throw-with.py @ d41735a

ADTast-experimental
Last change on this file since d41735a was b183717, checked in by Andrew Beach <ajbeach@…>, 3 years ago

Update another file in the exception benchmarks as well as some print formatting.

  • Property mode set to 100755
File size: 989 bytes
Line 
1#!/usr/bin/env python3
2
3# Throw Across With Statement (closest thing Python has to a destructor)
4
5from time import thread_time_ns
6
7
8class EmptyException(Exception):
9    pass
10
11
12class EmptyContextManager:
13
14    def __enter__(self):
15        pass
16
17    def __exit__(self, exception_type, exception_value, traceback):
18        pass
19
20
21def unwind_with(frames):
22    if 0 < frames:
23        with EmptyContextManager():
24            unwind_with(frames - 1)
25    else:
26        raise EmptyException()
27
28
29def main(argv):
30    times = 1
31    total_frames = 1
32    if 1 < len(argv):
33        times = int(argv[1])
34    if 2 < len(argv):
35        total_frames = int(argv[2])
36
37    start_time = thread_time_ns()
38    for count in range(times):
39        try:
40            unwind_with(total_frames)
41        except EmptyException:
42            pass
43
44    end_time = thread_time_ns()
45    print('Run-Time (s): {:.1f}'.format((end_time - start_time) / 1_000_000_000.))
46
47
48if '__main__' == __name__:
49    import sys
50    main(sys.argv)
Note: See TracBrowser for help on using the repository browser.