Skip to content

Commit 4f580cb

Browse files
Update runCode.js
1 parent 9196b99 commit 4f580cb

File tree

1 file changed

+28
-13
lines changed

1 file changed

+28
-13
lines changed

shared/runCode.js

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
// shared/runCode.js (patched)
2+
13
import fs from 'fs/promises';
24
import { exec as rawExec } from 'child_process';
35
import util from 'util';
@@ -7,32 +9,45 @@ export const exec = util.promisify(rawExec);
79
export const tempDir = new URL('../tmp/', import.meta.url).pathname;
810
await 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 ---------- */
1016
export 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';
2944
const clean = s =>
30-
s
31-
.split('\n')
32-
.filter(l => !/Execution Time|Memory Used/.test(l))
33-
.join('\n')
34-
.trim();
45+
s.split('\n')
46+
.filter(l => !/Execution Time|Memory Used/.test(l))
47+
.join('\n')
48+
.trim();
3549

50+
/* ---------- main runner ---------- */
3651
export 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, /Execution Time:\s*(.+?)\s*seconds/),
51-
memoryUsage: pick(stderr, /Memory Used:\s*(.+?)\s*KB/)
66+
memoryUsage: pick(stderr, /Memory Used:\s*(.+?)\s*KB/)
5267
};
5368
}

0 commit comments

Comments
 (0)