如果你希望用 JUnit 来测试一些性能问题,那么 JUnitBenchmark 可以帮到你,主要特性:
- 记录执行时间
- 监控垃圾收集
- 测试热身
-
示例测试:
01
package
org.javabenchmark;
02
03
import
com.carrotsearch.junitbenchmarks.AbstractBenchmark;
04
import
com.carrotsearch.junitbenchmarks.BenchmarkOptions;
05
import
javolution.text.TextBuilder;
06
import
org.junit.Test;
07
08
/**
09
* Benchmark for String concatenation. Compares StringBUilder (JDK) and
10
* TextBuilder (Javolution).
11
*/
12
public
class
StringConcatenationBenchmark
extends
AbstractBenchmark {
13
14
public
static
final
long
LOOPS_COUNT =
10000000
;
15
16
@Test
17
@BenchmarkOptions
(benchmarkRounds =
3
, warmupRounds =
1
)
18
public
void
stringBuilderBenchmark() {
19
20
StringBuilder builder =
new
StringBuilder();
21
for
(
long
i =
0
; i < LOOPS_COUNT; i++) {
22
builder.append(
'i'
).append(i);
23
}
24
System.out.println(builder.toString().length());
25
}
26
27
@Test
28
@BenchmarkOptions
(benchmarkRounds =
3
, warmupRounds =
1
)
29
public
void
textBuilderBenchmark() {
30
31
TextBuilder builder =
new
TextBuilder();
32
for
(
long
i =
0
; i < LOOPS_COUNT; i++) {
33
builder.append(
'i'
).append(i);
34
}
35
System.out.println(builder.toString().length());
36
}
37
}