@@ -86,9 +86,10 @@ def _generate_profiler_init(self) -> str:
8686 # Serialize line contents map for embedding in JavaScript
8787 line_contents_json = json .dumps (getattr (self , "line_contents" , {}))
8888
89- return f"""
89+ return f"""// @ts-nocheck
9090// Codeflash line profiler initialization
91- // @ts-nocheck
91+ const __codeflash_fs__ = require('fs');
92+ const __codeflash_path__ = require('path');
9293const { self .profiler_var } = {{
9394 stats: {{}},
9495 lineContents: { line_contents_json } ,
@@ -123,19 +124,18 @@ def _generate_profiler_init(self) -> str:
123124 this.lastLineTime = now;
124125
125126 this.totalHits++;
126- // Save every 100 hits to ensure we capture results even with --forceExit
127- if (this.totalHits % 100 === 0) {{
127+ // Save periodically to capture results even with --forceExit.
128+ // Use 10000 (not 100) to avoid excessive I/O on hot loops.
129+ if (this.totalHits % 10000 === 0) {{
128130 this.save();
129131 }}
130132 }},
131133
132134 save: function() {{
133- const fs = require('fs');
134- const pathModule = require('path');
135- const outputDir = pathModule.dirname('{ self .output_file .as_posix ()} ');
135+ const outputDir = __codeflash_path__.dirname('{ self .output_file .as_posix ()} ');
136136 try {{
137- if (!fs .existsSync(outputDir)) {{
138- fs .mkdirSync(outputDir, {{ recursive: true }});
137+ if (!__codeflash_fs__ .existsSync(outputDir)) {{
138+ __codeflash_fs__ .mkdirSync(outputDir, {{ recursive: true }});
139139 }}
140140 // Merge line contents into stats before saving
141141 const statsWithContent = {{}};
@@ -145,7 +145,7 @@ def _generate_profiler_init(self) -> str:
145145 content: this.lineContents[key] || ''
146146 }};
147147 }}
148- fs .writeFileSync(
148+ __codeflash_fs__ .writeFileSync(
149149 '{ self .output_file .as_posix ()} ',
150150 JSON.stringify(statsWithContent, null, 2)
151151 );
@@ -298,8 +298,11 @@ def parse_results(profile_file: Path) -> dict:
298298 return {"timings" : {}, "unit" : 1e-9 , "functions" : {}}
299299
300300 try :
301- with profile_file .open ("r" ) as f :
302- data = json .load (f )
301+ content = profile_file .read_text (encoding = "utf-8" ).strip ()
302+ if not content :
303+ logger .warning ("Line profiler output file is empty: %s" , profile_file )
304+ return {"timings" : {}, "unit" : 1e-9 , "functions" : {}}
305+ data = json .loads (content )
303306
304307 # Group by file and function
305308 timings = {}
0 commit comments