我在php中使用proc_open來調用java應用程序,將它傳遞給要處理的文本並讀取輸出文本。 Java執行時間非常長,我發現原因是讀取輸入需要大部分時間。我不確定它是php還是java的錯。php proc_open將輸入傳遞給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倍?有沒有辦法讓它更快?
您有建議** **兩次:'新的BufferedReader(新的InputStreamReader(System.in))' - 這可能是痛苦的。當然'String + ='而不是'StringBuilder'減慢了它的速度。 –