Skip to content

Commit 650ca9a

Browse files
committed
Added Async benchmark for future changes
1 parent ef846bf commit 650ca9a

1 file changed

Lines changed: 78 additions & 0 deletions

File tree

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package benchmark;
2+
3+
import graphql.execution.Async;
4+
import org.openjdk.jmh.annotations.Benchmark;
5+
import org.openjdk.jmh.annotations.BenchmarkMode;
6+
import org.openjdk.jmh.annotations.Level;
7+
import org.openjdk.jmh.annotations.Measurement;
8+
import org.openjdk.jmh.annotations.Mode;
9+
import org.openjdk.jmh.annotations.Param;
10+
import org.openjdk.jmh.annotations.Scope;
11+
import org.openjdk.jmh.annotations.Setup;
12+
import org.openjdk.jmh.annotations.State;
13+
import org.openjdk.jmh.annotations.Warmup;
14+
import org.openjdk.jmh.runner.Runner;
15+
import org.openjdk.jmh.runner.options.Options;
16+
import org.openjdk.jmh.runner.options.OptionsBuilder;
17+
18+
import java.util.ArrayList;
19+
import java.util.List;
20+
import java.util.concurrent.CompletableFuture;
21+
import java.util.concurrent.ExecutionException;
22+
import java.util.concurrent.TimeUnit;
23+
24+
@State(Scope.Benchmark)
25+
@BenchmarkMode(Mode.Throughput)
26+
@Warmup(iterations = 2)
27+
@Measurement(iterations = 2, timeUnit = TimeUnit.NANOSECONDS)
28+
public class AsyncBenchmark {
29+
30+
@Param({"0", "1", "10"})
31+
public int num;
32+
33+
List<CompletableFuture<Object>> futures;
34+
35+
@Setup(Level.Trial)
36+
public void setUp() throws ExecutionException, InterruptedException {
37+
futures = new ArrayList<>();
38+
for (int i = 0; i < num; i++) {
39+
futures.add(mkFuture(i));
40+
}
41+
42+
}
43+
44+
private CompletableFuture<Object> mkFuture(int i) {
45+
// half will take some time
46+
if (i % 2 == 0) {
47+
return CompletableFuture.supplyAsync(() -> sleep(i));
48+
} else {
49+
return CompletableFuture.completedFuture(i);
50+
}
51+
}
52+
53+
private Object sleep(int i) {
54+
try {
55+
Thread.sleep(i * 1000L);
56+
} catch (InterruptedException e) {
57+
throw new RuntimeException(e);
58+
}
59+
return i;
60+
}
61+
62+
@Benchmark
63+
public List<Object> benchmarkAsync() {
64+
Async.CombinedBuilder<Object> builder = Async.ofExpectedSize(futures.size());
65+
futures.forEach(builder::add);
66+
return builder.await().join();
67+
}
68+
69+
public static void main(String[] args) throws Exception {
70+
Options opt = new OptionsBuilder()
71+
.include("benchmark.AsyncBenchmark")
72+
.forks(5)
73+
.build();
74+
75+
new Runner(opt).run();
76+
}
77+
78+
}

0 commit comments

Comments
 (0)