2323
2424package jdk .jfr .event .profiling ;
2525import java .lang .management .ManagementFactory ;
26+ import java .lang .management .ThreadMXBean ;
2627import java .time .Duration ;
2728import java .time .Instant ;
2829import java .util .List ;
@@ -71,7 +72,7 @@ float rate() {
7172 }
7273
7374 /**
74- * Counting the events that are emitted for a given throttle in a given time.
75+ * Counting the events that are emitted for a given throttle in a given (CPU) time.
7576 * <p>
7677 * The result is wall-clock independent; it only records the CPU-time and the number of
7778 * emitted events. The result, therefore, does not depend on the load of the machine.
@@ -83,35 +84,30 @@ private static EventCount countEvents(int timeMs, String throttle) throws Except
8384 recording .enable (EventNames .CPUTimeSample )
8485 .with ("throttle" , throttle );
8586
86- var bean = ManagementFactory .getThreadMXBean ();
87-
8887 recording .start ();
8988
90- long startThreadCpuTime = bean .getCurrentThreadCpuTime ();
91-
92- wasteCPU (timeMs );
93-
94- long spendCPUTime = bean .getCurrentThreadCpuTime () - startThreadCpuTime ;
89+ long spendCPUTime = wasteCPU (timeMs );
9590
9691 recording .stop ();
9792
9893 long eventCount = Events .fromRecording (recording ).stream ()
9994 .filter (e -> e .getThread ().getJavaName ()
10095 .equals (Thread .currentThread ().getName ()))
10196 .count ();
102-
10397 return new EventCount (eventCount , spendCPUTime / 1_000_000_000f );
10498 }
10599 }
106100
107- private static void wasteCPU (int durationMs ) {
108- long start = System .currentTimeMillis ();
101+ private static long wasteCPU (int durationMs ) {
102+ ThreadMXBean bean = ManagementFactory .getThreadMXBean ();
103+ long start = bean .getCurrentThreadCpuTime ();
109104 double i = 0 ;
110- while (System . currentTimeMillis () - start < durationMs ) {
105+ while (bean . getCurrentThreadCpuTime () - start < durationMs * 1_000_000 ) {
111106 for (int j = 0 ; j < 100000 ; j ++) {
112107 i = Math .sqrt (i * Math .pow (Math .sqrt (Math .random ()), Math .random ()));
113108 }
114109 }
110+ return bean .getCurrentThreadCpuTime () - start ;
115111 }
116112
117113}
0 commit comments