当流源是a时,我无法实现流处理的良好并行化Reader.在四核CPU上运行下面的代码我首先观察到3个核心,然后突然下降到两个核心,然后是一个核心.整体CPU利用率徘徊在50%左右.
请注意示例的以下特征:
这意味着所有压力都在CPU上,I/O很小.这个例子是一个用于自动并行化的坐鸭.
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
... class imports elided ...
public class Main
{
static final AtomicLong totalTime = new AtomicLong();
public static void main(String[] args) throws IOException {
final long start = System.nanoTime();
final Path inputPath = createInput();
System.out.println("Start processing");
try (PrintWriter w = new PrintWriter(Files.newBufferedWriter(Paths.get("output.txt")))) {
Files.lines(inputPath).parallel().map(Main::processLine)
.forEach(w::println);
}
final double cpuTime = totalTime.get(),
realTime = System.nanoTime()-start;
final int cores = Runtime.getRuntime().availableProcessors();
System.out.println(" Cores: " + cores);
System.out.format(" CPU …Run Code Online (Sandbox Code Playgroud)