您好,登錄后才能下訂單哦!
測試1
@BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @Warmup(iterations = 5, time = 3, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 20, time = 3, timeUnit = TimeUnit.SECONDS) @Fork(1) @State(Scope.Benchmark) public class StreamBenchTest { List<String> data = new ArrayList<>(); @Setup public void init() { // prepare for(int i=0;i<100;i++){ data.add(UUID.randomUUID().toString()); } } @TearDown public void destory() { // destory } @Benchmark public void benchStream(){ data.stream().forEach(e -> { e.getBytes(); try { Thread.sleep(10); } catch (InterruptedException e1) { e1.printStackTrace(); } }); } @Benchmark public void benchParallelStream(){ data.parallelStream().forEach(e -> { e.getBytes(); try { Thread.sleep(10); } catch (InterruptedException e1) { e1.printStackTrace(); } }); } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(".*" +StreamBenchTest.class.getSimpleName()+ ".*") .forks(1) .build(); new Runner(opt).run(); } }
parallelStream線程數
默認是Runtime.getRuntime().availableProcessors() - 1,這里為7
運行結果
# Run complete. Total time: 00:02:44 Benchmark Mode Cnt Score Error Units StreamBenchTest.benchParallelStream avgt 20 155868805.437 ± 1509175.840 ns/op StreamBenchTest.benchStream avgt 20 1147570372.950 ± 6138494.414 ns/op
測試2
將數據data改為30,同時sleep改為100
Benchmark Mode Cnt Score Error Units StreamBenchTest.benchParallelStream avgt 20 414230854.631 ± 725294.455 ns/op StreamBenchTest.benchStream avgt 20 3107250608.500 ± 4805037.628 ns/op
可以發現sleep越長,parallelStream優勢越明顯。
小結
parallelStream在阻塞場景下優勢更明顯,其線程池個數默認為
Runtime.getRuntime().availableProcessors() - 1,如果需修改則需設置-Djava.util.concurrent.ForkJoinPool.common.parallelism=8
以上就是本次講述知識點的全部內容,感謝你對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。