@@ -23,10 +23,11 @@ def viztracer_profile(
2323 tracer = viztracer .VizTracer (max_stack_depth = depth , log_async = log_async )
2424
2525 tracer .start ()
26- yield
27- tracer .stop ()
28-
29- tracer .save (path () if callable (path ) else path )
26+ try :
27+ yield
28+ finally :
29+ tracer .stop ()
30+ tracer .save (path () if callable (path ) else path )
3031
3132
3233@contextmanager
@@ -45,31 +46,33 @@ def yappi_profile(
4546 yappi .set_clock_type ("wall" if wall_clock else "cpu" )
4647
4748 yappi .start ()
48- yield
49- yappi .stop ()
50-
51- threads = yappi .get_thread_stats ()
52- stats = {}
53- if separate_threads :
54- for thread in threads :
55- ctx_id = thread .id
56- stats [ctx_id ] = yappi .get_func_stats (ctx_id = ctx_id )
57- else :
58- stats [None ] = yappi .get_func_stats ()
59-
60- fpath = path () if callable (path ) else path
61- for ctx_id , st in stats .items ():
62- if fpath :
63- out = f"{ fpath } -{ ctx_id } " if ctx_id is not None else fpath
64- st .save (out , type = "callgrind" )
49+ try :
50+ yield
51+ finally :
52+ yappi .stop ()
53+
54+ threads = yappi .get_thread_stats ()
55+ stats = {}
56+ if separate_threads :
57+ for thread in threads :
58+ ctx_id = thread .id
59+ stats [ctx_id ] = yappi .get_func_stats (ctx_id = ctx_id )
6560 else :
66- if ctx_id is not None :
67- print (f"\n Thread { ctx_id } " ) # noqa: T201
68- st .print_all ()
69- if ctx_id is None :
70- threads .print_all ()
61+ stats [None ] = yappi .get_func_stats ()
62+
63+ fpath = path () if callable (path ) else path
64+ for ctx_id , st in stats .items ():
65+ if fpath :
66+ out = f"{ fpath } -{ ctx_id } " if ctx_id is not None else fpath
67+ st .save (out , type = "callgrind" )
68+ else :
69+ if ctx_id is not None :
70+ print (f"\n Thread { ctx_id } " ) # noqa: T201
71+ st .print_all ()
72+ if ctx_id is None :
73+ threads .print_all ()
7174
72- yappi .clear_stats ()
75+ yappi .clear_stats ()
7376
7477
7578@contextmanager
@@ -85,13 +88,15 @@ def instrument(html_output=False):
8588 profiler = Profiler ()
8689
8790 profiler .start ()
88- yield
89- profiler .stop ()
91+ try :
92+ yield
93+ finally :
94+ profiler .stop ()
9095
91- if html_output :
92- profiler .open_in_browser ()
93- return
94- print (profiler .output_text (unicode = True , color = True )) # noqa: T201
96+ if html_output :
97+ profiler .open_in_browser ()
98+ else :
99+ print (profiler .output_text (unicode = True , color = True )) # noqa: T201
95100
96101
97102@contextmanager
@@ -102,13 +107,14 @@ def profile(dump_path: Optional[str] = None):
102107 prof = cProfile .Profile ()
103108 prof .enable ()
104109
105- yield
106-
107- prof .disable ()
108- if not dump_path :
109- prof .print_stats (sort = "cumtime" )
110- return
111- prof .dump_stats (dump_path )
110+ try :
111+ yield
112+ finally :
113+ prof .disable ()
114+ if dump_path :
115+ prof .dump_stats (dump_path )
116+ else :
117+ prof .print_stats (sort = "cumtime" )
112118
113119
114120@contextmanager
0 commit comments