[英]How do I get the memory usage and cpu time of a process executed using ProcessBuilder?
I am executing python/perl scripts on java using processBuilder. 我正在使用processBuilder在Java上执行python / perl脚本。 I want to know the memory usage and CPU time for the process executed. 我想知道执行该过程的内存使用情况和CPU时间。 Java mx bean is limited to jvm. Java mx bean仅限于jvm。 Hence ,I don't think it can be used for script executions. 因此,我认为它不能用于脚本执行。 Please help. 请帮忙。
If you are using Java 9 or later, use Process::info()
to get the ProcessHandle.Info
object for the process (if available). 如果您使用的是Java 9或更高版本,请使用Process::info()
获取该流程的ProcessHandle.Info
对象(如果有)。 Depending on what the JVM supports on your OS platform, that may give you the total CPU time for the process, and the processes start time ... which you can use to calculate the elapsed time, under some circumstances. 根据JVM在您的OS平台上支持的功能,这可能会为您提供该进程的总CPU时间以及这些进程的启动时间...,在某些情况下,您可以使用它们来计算经过的时间。
Another alternative on a Linux system is to execute the command as "/usr/bin/time your command", and parse the last three lines of standard output to get the elapsed time, "user" CPU time and "system" CPU time. 在Linux系统上,另一种替代方法是将命令作为“ / usr / bin / time your command”执行,并解析标准输出的最后三行,以获取经过时间,“用户” CPU时间和“系统” CPU时间。
For example: 例如:
$ time date
Thu Jul 5 20:25:01 AEST 2018
real 0m0.002s
user 0m0.001s
sys 0m0.001s
Capture and parse the last 3 lines. 捕获并解析最后3行。 (Implementing this in Java is left as an exercise ...) (在Java中实现此操作作为练习...)
The GNU version of the time
command has options that can be used to show memory usage as well. GNU版本的time
命令具有可用于显示内存使用情况的选项。 This is described in the manual entry. 手册中对此进行了描述。
Some equivalent commands for Windows are described here: Windows的一些等效命令在此处介绍:
For the record, this (roughly speaking) is the way use time
using ProcessBuilder: 作为记录,这(大致而言)是使用ProcessBuilder的time
使用方式:
ProcessBuilder pb = new ProcessBuilder(
"sh", "-c", "/usr/bin/time python filename.py");
or 要么
ProcessBuilder pb = new ProcessBuilder(
"/usr/bin/time python filename.py");
If you are going to run commands in a subshell using "sh -c", the shell input string must be a single command argument . 如果要使用“ sh -c”在子shell中运行命令,则shell输入字符串必须是单个命令参数 。 Since ProcessBuilder
doesn't understand quoting, this means that you must do the splitting yourself; 由于ProcessBuilder
无法理解引用,因此这意味着您必须自己进行拆分。 see above. 往上看。
To get the GNU time to output the memory parameters, you need to use a format string, as described in "man time"; 要获得GNU输出内存参数的时间,您需要使用格式字符串,如“ man time”中所述; eg 例如
/usr/bin/time -f "%e %s %u %M" command to be run
Note that it is important to use "/usr/bin/time" rather than "time", since the builtin "time" command in some shells doesn't understand the "-f" option. 请注意,使用“ / usr / bin / time”而不是“ time”很重要,因为某些外壳程序中内置的“ time”命令无法理解“ -f”选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.