1+ // shared/runCode.js (patched)
2+
13import fs from 'fs/promises' ;
24import { exec as rawExec } from 'child_process' ;
35import util from 'util' ;
@@ -7,32 +9,45 @@ export const exec = util.promisify(rawExec);
79export const tempDir = new URL ( '../tmp/' , import . meta. url ) . pathname ;
810await fs . mkdir ( tempDir , { recursive : true } ) ;
911
12+ /* ---------- ONE helper that injects /usr/bin/time ---------- */
13+ const timer = '/usr/bin/time -f "Execution Time: %e seconds\\nMemory Used: %M KB"' ;
14+
15+ /* ---------- per‑language command builders ---------- */
1016export const languageConfigs = {
1117 cpp : {
1218 ext : '.cpp' ,
13- cmd : f =>
14- `/usr/bin/time -f "Execution Time: %e seconds\nMemory Used: %M KB" ` +
15- `g++ ${ f } -o ${ f } .out && ${ f } .out`
19+ cmd : f => `${ timer } g++ ${ f } -o ${ f } .out && ${ f } .out`
20+ } ,
21+
22+ python : {
23+ ext : '.py' ,
24+ cmd : f => `${ timer } python3 ${ f } `
1625 } ,
17- python : { ext : '.py' , cmd : f => `python3 ${ f } ` } ,
18- js : { ext : '.js' , cmd : f => `node ${ f } ` } ,
26+
27+ js : {
28+ ext : '.js' ,
29+ cmd : f => `${ timer } node ${ f } `
30+ } ,
31+
1932 java : {
2033 ext : '.java' ,
2134 cmd : f => {
2235 const cls = path . basename ( f , '.java' ) ;
23- return `javac ${ f } && java -cp ${ tempDir } ${ cls } ` ;
36+ // wrap with sh -c so /usr/bin/time measures both compile + run
37+ return `${ timer } sh -c "javac ${ f } && java -cp ${ tempDir } ${ cls } "` ;
2438 }
2539 }
2640} ;
2741
28- const pick = ( s , r ) => ( s . match ( r ) || [ ] ) [ 1 ] || 'N/A' ;
42+ /* ---------- helpers ---------- */
43+ const pick = ( s , r ) => ( s . match ( r ) || [ ] ) [ 1 ] || 'N/A' ;
2944const clean = s =>
30- s
31- . split ( '\n' )
32- . filter ( l => ! / E x e c u t i o n T i m e | M e m o r y U s e d / . test ( l ) )
33- . join ( '\n' )
34- . trim ( ) ;
45+ s . split ( '\n' )
46+ . filter ( l => ! / E x e c u t i o n T i m e | M e m o r y U s e d / . test ( l ) )
47+ . join ( '\n' )
48+ . trim ( ) ;
3549
50+ /* ---------- main runner ---------- */
3651export async function runCode ( code , language , jobId ) {
3752 const cfg = languageConfigs [ language ] ;
3853 if ( ! cfg ) throw new Error ( 'Unsupported language' ) ;
@@ -48,6 +63,6 @@ export async function runCode(code, language, jobId) {
4863 return {
4964 output : stdout . trim ( ) ,
5065 executionTime : pick ( stderr , / E x e c u t i o n T i m e : \s * ( .+ ?) \s * s e c o n d s / ) ,
51- memoryUsage : pick ( stderr , / M e m o r y U s e d : \s * ( .+ ?) \s * K B / )
66+ memoryUsage : pick ( stderr , / M e m o r y U s e d : \s * ( .+ ?) \s * K B / )
5267 } ;
5368}
0 commit comments