为什么对UUID.randomUUID()的初始调用会变慢?

Nic*_*aly 3 java performance uuid

给定以下生成a的代码片段,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;
}
Run Code Online (Sandbox Code Playgroud)

结果:

971
6
0
0
Run Code Online (Sandbox Code Playgroud)

JDK: 1.8 操作系统: Windows 7

为什么只有初始通话需要这么长时间?(将近1秒!)

Eug*_*ene 7

这是一次完成SecureRandom的初始化:

//from the source code of randomUUID
private static class Holder {
    static final SecureRandom numberGenerator = new SecureRandom();
}
Run Code Online (Sandbox Code Playgroud)

但这不是全部.那些零应该真的跳到你的脸上.因此操作耗时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();
    }
}
Run Code Online (Sandbox Code Playgroud)

输出说:

Benchmark          Mode  Cnt  Score   Error  Units
UUIDRandom.random  avgt    2  0.002          ms/op
UUIDRandom.random    ss    2  0.094          ms/op
Run Code Online (Sandbox Code Playgroud)

事实上,单次射击时间远远低于平均值.