- 性能测试
- java中自己写代码进行代码片段性能测试
- 使用jmh来进行性能测试
java 常用于互联网系统的后台编程,互联网应用往往意味着高并发的产生。在对一个系统进行设计和架构之前,我们需要对他的用户量,每个接口的访问流程以及访问速率进行预估。最大限度的保证系统在高并发下能稳定安全的运行。那么性能测试就是对系统的一种很好的预估,当然性能测试也能让我们发现代码中的一些缺陷和瓶颈点,让我们更好的对系统进行优化。
常用的性能测试工具jmeter和ab工具,这两样工具经常用于接口测试和并发测试。但是往往这些应用于接口,在测试的时候无法对代码的单一片段进行完美的测试,他可能还受带宽,网速以及丢包率的影响。
java中自己写代码进行代码片段性能测试通常我们在java中的性能测试的时候通常的做法是
long l = System.currentTimeMillis(); //do someThings long cost = System.currentTimeMillis() - l; System.out.println(cost);
在springboot中org.springframework.util.StopWatch就是采用这样的用法
public class StopWatch {
private final String id;
private boolean keepTaskList;
private final List taskList;
private long startTimeNanos;
......
private int taskCount;
private long totalTimeNanos;
......
}
public static final class TaskInfo {
private final String taskName;
private final long timeNanos;
}
或者测试粗化
long l = System.currentTimeMillis();
for(int i = 0; i < 10000; i++){
//do something
}
long cost = System.currentTimeMillis() - l;
System.out.println(cost);
使用jmh来进行性能测试
什么是jmh
jmh 即 (Java Microbenchmark Harness)中文大多数翻译为 JAVA 微基准测试套件,官方给出的解释是
JMH is a Java harness for building, running, and analysing nano/micro/milli/macro benchmarks written in Java and other languages targeting the JVM. (jmh 是 一种 用java以及其他JVM语言编写的用于构建运行和分析的一种工具)
github : https://github.com/openjdk/jmh
为什么要使用jmh- jmh来源于openjdk,有强大的后援支持
- jmh 测试可以达到纳秒级,
- jmh 提供了一套基于JVM测试的完美测试方案
- jmh 提供了一套性能测试的图表以及结果展示方案
样例代码org.openjdk.jmh jmh-core 1.23 org.openjdk.jmh jmh-generator-annprocess 1.23
https://github.com/openjdk/jmh/tree/master/jmh-samples/src/main/java/org/openjdk/jmh/samples
注解 Benchmark标记测试的方法
BenchmarkMode| 名称 | 解释 | 单位 |
|---|---|---|
| Mode.Throughput | operations per unit of time.(单位时间执行的次数) | ops/time |
| Mode.AverageTime | average time per per operation(每个方法执行的平均时间) | time/op |
| Mode.SampleTime | samples the time for each operation.(每个方法执行的时间) | time |
| Mode.SingleShotTime | measures the time for a single operation.(单个的执行时间) | |
| All | all the benchmark modes. (上面所有都执行一次) |
统计的时间单位
Warmup预热,因为java中涉及到JIT热编译。为了消除这部分代码的影响,我们需要对代码进行预热
| 参数 | 解释 |
|---|---|
| iterations | 预热次数 |
| time | 预热时间 |
| timeUnit | 预热时间单位 |
| batchSize | 同时预热 |
| 名称 | 描述 |
|---|---|
| Benchmark | 所有测试共享线程。做多线程的时候使用 |
| Group | 每一组中共享线程 |
| Thread | 每一个方法或者类共享线程 |
Setup marks the fixture method to be run before the benchmark.
在测试类运行前运行
TearDownTearDown marks the fixture method to be run after the benchmark.
在测试类后运行
OperationsPerInvocationOperationsPerInvocation annotations allows to communicate the benchmark does more than one operation, and let JMH to adjust the scores appropriately.
大致来说,就是把一个方法的执行时间按比例缩小N倍,如果一个方法中执行了循环,可能用到
Fork就是测试中产生进程的数量
GroupThreads
GroupThreads defines how many threads are participating in running a particular {@link Benchmark} method in the group
定义一个组内线程数
Measurement执行的次数,和预热参数一样。这里就不解释了
Param参数,定义入参。



