使用
测试的时候,每个线程都会进行一次参数初始化。由于对ct参数配置了3个数据,所以会测试三次,分别执行每个参数情况下的测试。下面的demo是1个线程。
每次测试的时候,启动一个JMH线程,先进行warmup,预热时迭代2次,每次迭代执行5s,也就是每次迭代时会执行5s的check方法。
Fork(1)表示每次测试用几个进程,相当于上面的测试逻辑进行几次。
State注解是因为,这个demo中用了@Setup注解:Scope.Benchmark表示,这次@Setup初始化的参数会应在本次测试的所有JMH工作线程上,也就是所有JMH工作线程共享这个初始值。
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 2, time = 5, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 5, timeUnit = TimeUnit.SECONDS)
@Threads(1)
@Fork(1)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
public class Jmh {
ExecutorService executor;
@Param({"10000", "100000", "1000000"})
int ct;
AtomicInteger count;
@Benchmark
public void noCheck() {
System.setProperty("check", "false");
test();
}
@Benchmark
public void check() {
System.setProperty("check", "true");
test();
}
private void test() {
final CountDownLatch countDownLatch = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
executor.execute(new Runnable() {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
if (count.incrementAndGet() >= ct) {
break;
}
}
countDownLatch.countDown();
}
});
}
try {
// 这里是await方法,不是wait方法。😓
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Setup
public void prepare() {
mscExecutor = Executors.newFixedThreadPool(10);
count = new AtomicInteger(0);
System.out.println("ct: " + ct);
}
@TearDown
public void shutdown() {
executor.shutdownNow();
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(Jmh.class.getSimpleName())
.build();
Collection<RunResult> results = new Runner(opt).run();
try {
ResultExporter.exportResult("executor test", results, "ct", "ops/ms");
} catch (Exception e) {
e.printStackTrace();
}
}
}
生成图片
可以使用 导出图片的github地址 导出图片。