给定以下代码片段,它生成一个UUID.randomUUID(),我得到以下性能结果(以毫秒为单位):
public static void main(String[] args) {
long tmp = System.currentTimeMillis();
UUID.randomUUID();
tmp = printDiff(tmp);
UUID.randomUUID();
tmp = printDiff(tmp);
UUID.randomUUID();
tmp = printDiff(tmp);
UUID.randomUUID();
tmp = printDiff(tmp);
}
private static long printDiff(final long previousTimestamp) {
long tmp = System.currentTimeMillis();
System.out.printf("%s%n", tmp - previousTimestamp);
return tmp;
}
结果:
971
6
0
0
JDK:1.8
操作系统:Windows 7
为什么只有初始通话需要这么长时间? (将近1秒!)
解决方法:
这是一次完成SecureRandom的初始化:
//from the source code of randomUUID
private static class Holder {
static final SecureRandom numberGenerator = new SecureRandom();
}
但这不是全部.那些零应该真的跳到你的脸上.因此操作耗时0毫秒;这是否意味着他们减少了?像几纳秒或你做错了什么?
有一个适当的工具来衡量这些东西,称为jmh.
@BenchmarkMode({ Mode.AverageTime, Mode.SingleShotTime })
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 2, time = 2, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 2, time = 2, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class UUIDRandom {
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder().include(UUIDRandom.class.getSimpleName()).build();
new Runner(opt).run();
}
@Benchmark
@Fork(1)
public UUID random() {
return UUID.randomUUID();
}
}
输出说:
Benchmark Mode Cnt Score Error Units
UUIDRandom.random avgt 2 0.002 ms/op
UUIDRandom.random ss 2 0.094 ms/op
事实上,单次射击时间远远低于平均值.
标签:java,performance,uuid
来源: https://codeday.me/bug/20190727/1552951.html