@@ -26,42 +26,51 @@ def catch_context():
2626 pass
2727
2828
29- def with_catch (fn ):
29+ def with_contextlib_contextmanager (fn ):
3030 with catch_context ():
3131 fn ()
3232
3333
34- class ManualCatchContext ( object ) :
34+ class ManualContextManager :
3535 def __enter__ (self ):
3636 pass
3737
3838 def __exit__ (self , exc_type , exc_val , exc_tb ):
3939 return True
4040
4141
42- def manual_with_catch (fn ):
43- with ManualCatchContext ():
42+ def with_manual_contextmanager (fn ):
43+ with ManualContextManager ():
4444 fn ()
4545
4646
47- preinstantiated_manual_catch_context = ManualCatchContext ()
47+ preinstantiated_manual_contextmanager = ManualContextManager ()
4848
4949
50- def manual_with_catch_cache (fn ):
51- with preinstantiated_manual_catch_context :
50+ def with_preinstantiated_manual_contextmanager (fn ):
51+ with preinstantiated_manual_contextmanager :
5252 fn ()
5353
5454
55- setup = "from __main__ import simple_catch, work_pass, work_fail, with_catch, manual_with_catch, manual_with_catch_cache "
56- commands = [
55+ setup = "from __main__ import simple_catch, work_pass, work_fail, with_contextlib_contextmanager, with_manual_contextmanager, with_preinstantiated_manual_contextmanager "
56+ tests = [
5757 "simple_catch(work_pass)" ,
5858 "simple_catch(work_fail)" ,
59- "with_catch (work_pass)" ,
60- "with_catch (work_fail)" ,
61- "manual_with_catch (work_pass)" ,
62- "manual_with_catch (work_fail)" ,
63- "manual_with_catch_cache (work_pass)" ,
64- "manual_with_catch_cache (work_fail)" ,
59+ "with_contextlib_contextmanager (work_pass)" ,
60+ "with_contextlib_contextmanager (work_fail)" ,
61+ "with_manual_contextmanager (work_pass)" ,
62+ "with_manual_contextmanager (work_fail)" ,
63+ "with_preinstantiated_manual_contextmanager (work_pass)" ,
64+ "with_preinstantiated_manual_contextmanager (work_fail)" ,
6565]
66- for c in commands :
67- print (c , ": " , timeit .timeit (c , setup ))
66+
67+ results = {}
68+ for test_stmt in tests :
69+ times = timeit .repeat (
70+ setup = setup , stmt = test_stmt , repeat = 100 , number = 10000 , globals = {}
71+ )
72+ avg_time = sum (times ) / len (times )
73+ results [test_stmt ] = avg_time
74+
75+ for test_name , result in sorted (results .items (), key = lambda x : x [1 ]):
76+ print (f"{ test_name :>18} : { result :03g} " )
0 commit comments