【发布时间】:2014-12-24 07:33:36
【问题描述】:
我在 Java 中的代码执行器中工作。问题是如何控制这个执行的执行时间和内存使用。
我正在做这样的事情:
public ExecutionResult execute(List<String> args, String inputFile) throws CommandLineExecutorException {
try {
ProcessBuilder builder = new ProcessBuilder(args);
if (inputFile != null) {
builder.redirectInput(new File(inputFile));
}
final long startTime = System.currentTimeMillis();
Process process = builder.start();
process.waitFor();
final long endTime = System.currentTimeMillis();
int exitValue = process.exitValue();
InputStream inputStream = exitValue == 0 ? process.getInputStream() : process.getErrorStream();
String consoleOutput = readStream(inputStream);
return new ExecutionResult(exitValue, consoleOutput, (endTime - startTime));
} catch (IOException | InterruptedException ex) {
throw new CommandLineExecutorException(ex.getMessage());
}
}
我不确定这是否是控制子流程执行时间的最佳方式。对于内存,我仍在寻找最佳选择。
当我使用 php 时,我曾经使用脚本通过 linux 命令来控制内存和时间,但我想知道在 java 中是否有更好的方法来实现这一点。
【问题讨论】: