【问题标题】:Get memory usage and execution time from a process initiated with the ProcessBuilder从使用 ProcessBuilder 启动的进程中获取内存使用情况和执行时间
【发布时间】: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 中是否有更好的方法来实现这一点。

【问题讨论】:

    标签: java memory-management


    【解决方案1】:

    为了监控子 Java 进程,您可以使用 Java JMX 来查询 JVM 进程的各种参数。请参阅this answer 了解如何连接到远程 JVM 和this one 以获取内存信息。

    要监控非 Java 进程,您可以使用 SIGAR 多平台 API。

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 2023-03-27
      • 1970-01-01
      • 2011-04-26
      • 2015-03-11
      • 2010-10-24
      • 1970-01-01
      • 2011-05-07
      • 2013-04-25
      相关资源
      最近更新 更多