【发布时间】:2013-08-06 08:52:47
【问题描述】:
我在 php 中使用 proc_open 来调用 java 应用程序,将要处理的文本传递给它并读取输出文本。 Java 执行时间很长,我发现其原因是读取输入花费了大部分时间。不知道是php的问题还是java的问题。
我的 PHP 代码:
$process_cmd = "java -Dfile.encoding=UTF-8 -jar test.jar";
$env = NULL;
$options = ["bypass_shell" => true];
$cwd = NULL;
$descriptorspec = [
0 => ["pipe", "r"], //stdin is a pipe that the child will read from
1 => ["pipe", "w"], //stdout is a pipe that the child will write to
2 => ["file", "java.error", "a"]
];
$process = proc_open($process_cmd, $descriptorspec, $pipes, $cwd, $env, $options);
if (is_resource($process)) {
//feeding text to java
fwrite($pipes[0], $input);
fclose($pipes[0]);
//reading output text from java
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$return_value = proc_close($process);
}
我的java代码:
public static void main(String[] args) throws Exception {
long start;
long end;
start = System.currentTimeMillis();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String in;
String input = "";
br = new BufferedReader(new InputStreamReader(System.in));
while ((in = br.readLine()) != null) {
input += in + "\n";
}
end = System.currentTimeMillis();
log("Input: " + Long.toString(end - start) + " ms");
start = System.currentTimeMillis();
org.jsoup.nodes.Document doc = Jsoup.parse(input);
end = System.currentTimeMillis();
log("Parser: " + Long.toString(end - start) + " ms");
start = System.currentTimeMillis();
System.out.print(doc);
end = System.currentTimeMillis();
log("Output: " + Long.toString(end - start) + " ms");
}
我正在传递 3800 行的 java html 文件(作为独立文件的大小约为 200KB)。这些是日志文件中细分的执行时间:
Input: 1169 ms
Parser: 98 ms
Output: 12 ms
我的问题是:为什么输入比输出长 100 倍?有没有办法让它更快?
【问题讨论】:
-
你有 两次:
new BufferedReader(new InputStreamReader(System.in))- 这可能会很痛苦。当然String +=而不是StringBuilder会减慢它的速度。